How can I handle empty response body with Retrofit 2? How can I handle empty response body with Retrofit 2? android android

How can I handle empty response body with Retrofit 2?


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


If you use RxJava, then it's better to use Completable in this case

Represents a deferred computation without any value but only indication for completion or exception. The class follows a similar event pattern as Reactive-Streams: onSubscribe (onError|onComplete)?

http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Completable.html

in the accepted answer:

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

If the endpoint returns failure response code, it will still be in the onNext and you will have to check the response code yourself.

However, if you use Completable.

@GET("/path/to/get")Completable getMyData(/* your args here */);

you will have only onComplete and onError.if the response code is success it will fire the onComplete else it will fire onError.


If you are using rxjava, use something like :

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