How can I get the response code from a VolleyError?

Bart Burg picture Bart Burg · Mar 12, 2014 · Viewed 11.5k times · Source

I'm looking for a way to get the response code of a thrown VolleyError. My ErrorListener looks like this:

Response.ErrorListener errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        error.printStackTrace();
        //Get response code here
        VolleyLog.e("Error: ", error.toString());
        VolleyLog.e("Error: ", error.getLocalizedMessage());
    }
};

The 2 lines I send to my VolleyLog print the following:

03-12 10:57:56.932: E/Volley(7147): [1] 1.onErrorResponse: Error: 
03-12 10:57:56.932: E/Volley(7147): [1] 1.onErrorResponse: Error: 

Volley does know what comes back because I can also see the following in my VolleyLog:

03-12 10:57:56.692: E/Volley(7147): [41854] BasicNetwork.performRequest: Unexpected response code 403 for https://*******/Employee/authenticate
03-12 10:57:56.897: E/Volley(7147): [41854] BasicNetwork.performRequest: Unexpected response code 403 for https://*******/Employee/authenticate
03-12 10:57:56.902: W/System.err(7147): com.android.volley.AuthFailureError
03-12 10:57:56.902: W/System.err(7147):     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:143)
03-12 10:57:56.902: W/System.err(7147):     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

So basically, what I want is to get that response code "403" (Forbidden).

Answer

Blackbelt picture Blackbelt · Mar 12, 2014

through the VolleyError:

error.networkResponse.statusCode

looking at the source code, I saw that VolleyError has a public final member NetworkResponse called networkResponse, that holds that statusCode of the Http call. You should check for NPE.

Here you can find the source code for the NetworkResponse. Here you can find the source code for the VolleyError