Sindri Þór
Sindri Þór

Reputation: 2927

Retrofit - Keep getting empty body from API

I've been trying out Retrofit for now one and half day now but Retrofit seems to disliking my programming methods.

I'm getting Status code: 200 and no errors but body is always empty. I've tried different APIs so I'm sure that this is some architecture failure in my short code.

Note: Using gitResult here and there, why? I was using Githubs API earlier.

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'

}

To be clear:

Problem: body is always empty.

Below is a copy of my code, I appreciate any suggestions.

public class MainActivity extends AppCompatActivity {

    private UserAdapter adapter ;
    List<Item> Users ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ListView listView = (ListView) findViewById(R.id.listView);
        Users = new ArrayList<Item>();


        final ProgressDialog dialog = ProgressDialog.show(this, "", "loading...");


        RestClient.GitApiInterface service = RestClient.getClient();
        Call<GitResult> call = service.getUsersNamedTom();

        call.enqueue(new Callback<GitResult>() {
            @Override
            public void onResponse(Response<GitResult> response) {
                dialog.dismiss();
                Log.d("MainActivity", "Status Code = " + response.code());
                if (response.isSuccess()) {
                    // request successful (status code 200, 201)
                    GitResult result = response.body();
                    Log.d("MainActivity", "response = " + new Gson().toJson(result));
                    //Users = result.getItems();
                    Log.d("MainActivity", "Items = " + Users.size());
                    adapter = new UserAdapter(MainActivity.this, Users);
                    listView.setAdapter(adapter);
                } else {
                    // response received but request not successful (like 400,401,403 etc)
                    //Handle errors
                }
            }

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

..

public class GitResult {

    private int totalCount;
    private boolean incompleteResults;
    private List<Item> items = new ArrayList<Item>();

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public boolean isIncompleteResults() {
        return incompleteResults;
    }

    public void setIncompleteResults(boolean incompleteResults) {
        this.incompleteResults = incompleteResults;
    }

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }
}


public final class ToStringConverter implements Converter<String> {

    @Override
    public String fromBody(ResponseBody body) throws IOException {
        return body.string();
    }

    @Override
    public RequestBody toBody(String value) {
        return RequestBody.create(MediaType.parse("text/plain"), value);
    }
}

..

public class RestClient {

    private static GitApiInterface gitApiInterface ;
    private static String baseUrl = "http://jsonplaceholder.typicode.com" ;

    public static GitApiInterface getClient() {
        if (gitApiInterface == null) {

            OkHttpClient okClient = new OkHttpClient();
            okClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response response = chain.proceed(chain.request());
                    return response;
                }
            });

            Retrofit client = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverter(String.class, new ToStringConverter())
                    .client(okClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            gitApiInterface = client.create(GitApiInterface.class);
        }
        return gitApiInterface ;
    }

    public interface GitApiInterface {

        @GET("/posts/1")
        Call<GitResult> getUsersNamedTom();

Upvotes: 3

Views: 1565

Answers (3)

Hitesh Sahu
Hitesh Sahu

Reputation: 45072

I had same problem the issue was JSON mapping by GSON was faulty . JSON Object key send by server and what I was using was mismatched.

If the response Code is HTTP_OK but response body is wrong , that means there is problem while parsing response. Double check if JSON key/properties from response matches with key mapping in model.

Upvotes: 1

faranjit
faranjit

Reputation: 1627

I think the problem can be here:

.addConverter(String.class, new ToStringConverter())

Try to convert to GitResult class or try like this:

Retrofit client = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Upvotes: 4

ThaiPD
ThaiPD

Reputation: 3751

I tried to connect to http://jsonplaceholder.typicode.com/posts/1 and get the response as:

   {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

So I think your GitResult class was not match with Response from Server. I suggest you should change your GitResult class as below

public class GitResult {
    public int getUserId() { 
         return this.userId 
    }
    public int setUserId(int userId) { 
         this.userId = userId 
    }
    int userId;


    public int getId() { 
         return this.id 
    }
    public int setId(int id) { 
         this.id = id 
    }
    int id;


    public String getTitle() { 
         return this.title 
    }
    public String setTitle(String title) { 
         this.title = title 
    }
    String title;


    public String getBody() { 
         return this.body 
    }
    public String setBody(String body) { 
         this.body = body 
    }
    String body;

}

Hope it help!

Upvotes: 1

Related Questions