Search code examples
androidretrofitretrofit2

How to get Retrofit success response status codes


I am not able to get success response status code from response like 200,201.. etc. As we can easily get error codes from RetrofitError class like error.isNetworkError() and error.getResponse().getStatus(). Is there any workaround for getting status codes?


Solution

  • As per Retrofit 2.0.2, the call is now

    @Override
    public void onResponse(Call<YourModel> call, Response<YourModel> response) {
        if (response.code() == 200) {
           // Do awesome stuff
        } else {
           // Handle other response codes
        }
    }
    

    Hope it helps someone :-)

    EDIT: Many apps could also benefit from just checking for success (response code 200-300) in one clause, and then handling errors in other clauses, as 201 (Created) and 202 (Accepted) would probably lead to the same app logic as 200 in most cases.

    @Override
    public void onResponse(Call<YourModel> call, Response<YourModel> response) {
        if (response.isSuccessful()) {
           // Do awesome stuff
        } else if (response.code() == 401) {
           // Handle unauthorized
        } else {
           // Handle other responses
        }
    }