Xantosh Lamsal
Xantosh Lamsal

Reputation: 349

Unable to perform POST request with retrofit android

While I am trying to perform the post request with retrofit, it is throwing timeout exception. While using postman the API Url is working perfectly fine. Is there any error in the code. This is my code:

ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("accessToken", token);
    Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}
Call<ResponseBody> callUser = apiInterface.facebookLogin(jsonObject);
dialog.show();
callUser.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.code() == 200) 
        Log.e("Token Object", response.toString());
        dialog.dismiss();
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Toast.makeText(getContext(), "Sorry! Somme Error Occured" + t.toString(), Toast.LENGTH_LONG).show();
        dialog.dismiss();
    }
});

This is the interface:

//facebook login
@POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(@Body JSONObject jsonObject);

This is the Retrofit Client

public class ApiClient {
    public static final String BASE_URL = "http://192.168.100.15:8000/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100,TimeUnit.SECONDS).build();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

This is the successful postman request enter image description here

Upvotes: 0

Views: 187

Answers (1)

Yamini Balakrishnan
Yamini Balakrishnan

Reputation: 2411

Pass the request parameters as RequestBody as follows:

@POST("/api/users/facebooklogin")
Call<ResponseBody> facebookLogin(@Body RequestBody request);
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("accessToken", token);
    Log.e("Token Object", jsonObject.toString());
} catch (JSONException e) {
    e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
Call<ResponseBody> callUser = apiInterface.facebookLogin(requestBody);

Upvotes: 1

Related Questions