Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle empty response body with Retrofit 2?

Recently I started using Retrofit 2 and I faced an issue with parsing empty response body. I have a server which responds only with http code without any content inside the response body.

How can I handle only meta information about server response (headers, status code etc)?

like image 300
Yevgen Derkach Avatar asked Oct 06 '22 17:10

Yevgen Derkach


People also ask

What is @body in retrofit?

The @Body annotation defines a single request body. interface Foo { @POST("/jayson") FooResponse postJson(@Body FooRequest body); } Since Retrofit uses Gson by default, the FooRequest instances will be serialized as JSON as the sole body of the request.

Is retrofit a REST client?

Retrofit is a REST Client for Java and Android allowing to retrieve and upload JSON (or other structured data) via a REST based You can configure which converters are used for the data serialization, example GSON for JSON.


1 Answers

Edit:

As Jake Wharton points out,

@GET("/path/to/get")
Call<Void> getMyData(/* your args here */);

is the best way to go versus my original response --

You can just return a ResponseBody, which will bypass parsing the response.

@GET("/path/to/get")
Call<ResponseBody> getMyData(/* your args here */);

Then in your call,

Call<ResponseBody> dataCall = myApi.getMyData();
dataCall.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        // use response.code, response.headers, etc.
    }

    @Override
    public void onFailure(Throwable t) {
        // handle failure
    }
});
like image 128
iagreen Avatar answered Oct 18 '22 06:10

iagreen