65

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Adarsh Yadav
  • 3,752
  • 3
  • 24
  • 46

4 Answers4

104

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
    }
}
jhm
  • 4,379
  • 5
  • 33
  • 49
20

You can get the status code in success() just like you do it in failure()

@Override
public void success(Object object, Response response) {
    response.getStatus() // returns status code integer
}

Since you have a Response object in success callback as response.getStatus()

EDIT

I assume you are using okhttp with retrofit.

okhttp has a powerful tool called Interceptor

You can catch the response before retrofits Callback and get status code from the response:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new  Interceptor(){
    @Override 
    public Response intercept(Chain chain) throws IOException{

    Request request = chain.request();
    Response response = chain.proceed(request);
    response.code()//status code
    return response;

});

// then add it to you Restclient like this:
restAdapter = new RestAdapter.Builder()
                .setEndpoint(URL_SERVER_ROOT)
                .setClient(new OkClient(client))  //plus your configurations       
                .build();

To learn more about interceptors visit here.

Yvan Lourenço
  • 190
  • 1
  • 9
Ercan
  • 3,705
  • 1
  • 22
  • 37
  • I didn't find any function response.getStatus(). I am using retrofit 1.9.0 ,which version are you using? – Adarsh Yadav Aug 04 '15 at 12:28
  • I am using 1.9.0 too. are you using the Callback interface? – Ercan Aug 04 '15 at 12:40
  • 1
    Yes, but as per http://square.github.io/retrofit/javadoc/retrofit/Callback.html document we have two callbacks success and failure.As per definition we have will get Unsuccessful HTTP response due to network failure, non-2XX status code, or unexpected exception from failure but only Successful HTTP response from success. – Adarsh Yadav Aug 04 '15 at 12:49
  • ah sorry i didnt get the question right i think. now i will edit my answer – Ercan Aug 04 '15 at 12:50
  • Yeh, actually just like failure status code i need success status codes for doing some operations on the basis of them. On other hand thanks for spending your time on it. – Adarsh Yadav Aug 04 '15 at 12:52
  • 1
    But I am pretty sure success call back has 2 parameters 1st one is your type 2nd is the Response as the documentation says: success(T t, Response response) – Ercan Aug 04 '15 at 13:04
  • Is there any complete tutorial for using Okhttp interceptor? – Adarsh Yadav Aug 04 '15 at 13:22
  • @AdarshYadav read that documentation again. on success you do receive the Response object that contains what you ask for. – njzk2 Aug 04 '15 at 13:34
  • The "T" is what you asked for, "Response" is as same as RetrofitError.getResponse. in response object you have status code. please try using it I am sure i am using it in my code. – Ercan Aug 04 '15 at 13:42
  • @Ercan: above code works for me, now I am able to get status code but now my app start crashing Retrofit﹕ java.lang.IllegalArgumentException: method POST must have a request body. I am using following combinations compile'com.squareup.retrofit:retrofit:1.9.0' compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0' compile 'com.squareup.picasso:picasso:2.5.0' .Is this issue related to different versions. – Adarsh Yadav Aug 05 '15 at 06:19
  • I am not sure @AdarshYadav this looks like another question to me. It clearly states that post method lacking a body. Check your service method name and request. use restClient in full Log mode. I hope this helps you. – Ercan Aug 05 '15 at 06:23
  • 1
    I Have fixed it by reducing versions to compile 'com.squareup.okhttp:okhttp:2.2.0' and compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0' .Thanks for your efforts. – Adarsh Yadav Aug 05 '15 at 06:35
  • RestAdapter is deprecated – Barungi Stephen Dec 30 '19 at 09:49
  • @stevebaros, this answer is almost 5 years old by now. – Ercan Jan 03 '20 at 09:44
  • Thanks for `Interceptor`. I found status code when parsed HTML instead of JSON. In this case it threw `JsonSyntaxException`. – CoolMind Aug 15 '22 at 17:48
9

i achieved it by following codes:

public abstract class BaseCallBack<T> {

    public abstract void onSuccess(Response<T> response);
    public abstract void onFailure(Response<T> response);
}

public abstract class SuccessCallback<T> extends BaseCallBack<T> implements Callback<T>{


    @Override
    public void onResponse(Call<T> call, Response<T> response) {

        if(response.code()>= 400 && response.code() < 599){
             onFailure(response);
        }
        else {
            onSuccess(response);
        }

    }

    @Override
    public void onFailure(Call<T> call, Throwable t){

    }

    @Override
    public void onSuccess(Response<T> response) {

    }

    @Override
    public void onFailure(Response<T> response) {

    }
}

When the rest api returns 400 etc then the onFailure method will be call by default. If you wanna do something onsuccess:(when returns 200 etc)

 ServiceConnector.api.getHomePage().enqueue(new SuccessCallback<Void>() {
        @Override
        public void onSuccess(Response<Void> response) {
            super.onSuccess(response);
        }
    });
gonczor
  • 3,994
  • 1
  • 21
  • 46
aligur
  • 3,387
  • 3
  • 34
  • 51
1

you should get exception code iin onError response

HttpException httpException =((HttpException) e).code();
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30665677) – Kaamel Dec 25 '21 at 21:54