Unable to perform POST request with retrofit android

时间:2017-11-13 06:45:45

标签: android android-studio retrofit retrofit2 androidhttpclient

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

1 个答案:

答案 0 :(得分:1)

将请求参数传递为RequestBody,如下所示:

@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);