How to get Retrofit success response status codes

前端 未结 3 1607
谎友^
谎友^ 2020-11-27 17:51

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.i

3条回答
  •  温柔的废话
    2020-11-27 18:30

    As per Retrofit 2.0.2, the call is now

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

提交回复
热议问题