android – How to access the contents of an error response in Volley?-ThrowExceptions

Exception or error:

Using any of these examples:
http://developer.android.com/training/volley/request.html

I understand how to process the response of a succesful request, and how to detect and react to an error.

However, an error may be (among other situations) a 40x or 50x response from the server, in which case the response can still contain data (headers and body).

But the error listener is only passed a VolleyError object (which is a subclass of Exception if I’m not mistaken) and not a Response object.

How do I access the content of an error response?

How to solve:

In StringRequest for example:

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    Map<String, String> responseHeaders = response.headers;
    if (response.statusCode == 401) {
        // Here we are, we got a 401 response and we want to do something with some header field; in this example we return the "Content-Length" field of the header as a successfully response to the Response.Listener<String>
        Response<String> result = Response.success(responseHeaders.get("Content-Length"), HttpHeaderParser.parseCacheHeaders(response));
        return result;
    } // else any other code that carries a message
    return super.parseNetworkResponse(response);
}

###

The VolleyError object has a networkResponse reference, which itself has a ‘data’ member, which is a byte array of the response body. If you want to view the data in the case of an error code in response, you can use something like this:

@Override
public void onErrorResponse(VolleyError error) {
    String body;
    //get status code here
    String statusCode = String.valueOf(error.networkResponse.statusCode);
    //get response body and parse with appropriate encoding
    if(error.networkResponse.data!=null) {
        try {
            body = new String(error.networkResponse.data,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    //do stuff with the body...
}

Leave a Reply

Your email address will not be published. Required fields are marked *