Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp response status code in onFailure method

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 ?

like image 306
YiFeng Avatar asked Apr 22 '16 06:04

YiFeng


Video Answer


2 Answers

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.

like image 135
yennsarah Avatar answered Oct 19 '22 22:10

yennsarah


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.

like image 23
mrEvgenX Avatar answered Oct 19 '22 22:10

mrEvgenX