OkHttp response status code in onFailure method

14,606

Solution 1

As far as I remember, onFailure gets triggered when you get no response. So, if your receive an error, onResponse will be called. You can do something like this in onResponse:

@Override
public void onResponse(Call call, Response response) throws IOException {
    switch(response.code()){
    //your desired catched codes here.

   }
}

And official doc for onResponse method:

Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: response may still indicate an unhappy HTTP response code like 404 or 500.

Solution 2

https://github.com/square/okhttp/issues/1769

According to the link, above, onFailure() is called if and only if there were problems with the client.

If the request was successfully delivered but there was a server problem you can check response.isSuccessful(). If it returns false, check response.code() and handle the error.

Share:
14,606
YiFeng
Author by

YiFeng

Updated on June 07, 2022

Comments

  • YiFeng
    YiFeng about 2 years

    when I user the OkHttp Library with a asynchronous way like this:

    call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
    
            }
        });
    

    In the onFailure method, how I get the response status code to distinguish different errors. For example, Network error or Server error ?