Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving an empty body in retrofit Response

I am using retrofit to get data from http URL. My Interface Class :

public interface SlotsAPI {

    /*Retrofit get annotation with our URL
      And our method that will return a Json Object
    */
    @GET(url)
    retrofit.Call<JSONObject> getSlots();
}

My request method.

public void getResponse(){

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

    //Creating an object of our api interface
    SlotsAPI api = retrofit.create(SlotsAPI.class);
    retrofit.Call<JSONObject> callback = api.getSlots();
    callback.enqueue(new Callback<JSONObject>() {
    @Override
    public void onResponse(Response<JSONObject> response) {
        if (response != null) {
            Log.d("OnResponse", response.body().toString());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
    });
}

In the response I am receiving an empty body.And the server responds with 200 OK.

D/OnResponse: {}

But when I open the URL in browser I am getting JSONObject on the screen.

like image 502
Viking93 Avatar asked Mar 14 '16 20:03

Viking93


People also ask

How do I send a body in post request in retrofit?

Request Body@POST("users/new") Call<User> createUser(@Body User user); The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.

What is the purpose of a retrofit interface?

Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp.

What is @streaming in retrofit?

The interface for Retrofit REST service, in this case, the GET, the @Streaming enables the downloading for large file. public interface RetrofitInterface { @Streaming @GET Call<ResponseBody> downloadFileByUrl(@Url String fileUrl); }


2 Answers

Please check your JsonObject. If you want to get response in json you must be define a response type JsonObject not JSONObject other wise specify the pojo class in your interface.

like image 100
Ashik Abbas Avatar answered Oct 13 '22 01:10

Ashik Abbas


you should try like this way ....

public interface SlotsAPI {

/*Retrofit get annotation with our URL
  And our method that will return a Json Object
*/
@GET(url)
Call<JsonElement> getSlots();
}

in request method

 retrofit.Call<JsonElement> callback = api.getSlots();
callback.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Response<JsonElement> response) {
    if (response != null) {
        Log.d("OnResponse", response.body().toString());
    }
}
like image 20
curiousMind Avatar answered Oct 13 '22 02:10

curiousMind