How to get status code in successful response Volley Android

1daemon1 picture 1daemon1 · Aug 12, 2014 · Viewed 14.8k times · Source

I would like to ask how to get status code when using Volley.

I have following code:

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Here I want to get status code
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }
    )

Is it possible ? If not, why ?

Answer

1daemon1 picture 1daemon1 · Aug 13, 2014

Maybe this class instead of StringResponse:

public class NetworkResponseRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;

public NetworkResponseRequest(int method, String url, Response.Listener<NetworkResponse> listener,
                     Response.ErrorListener errorListener) {
    super(method, url, errorListener);
    mListener = listener;
}

public NetworkResponseRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
    this(Method.GET, url, listener, errorListener);
}

@Override
protected void deliverResponse(NetworkResponse response) {
    mListener.onResponse(response);
}

@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
    return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
}

public static String parseToString(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        parsed = new String(response.data);
    }
    return parsed;
}
}

Usage:

NetworkResponseRequest request = new NetworkResponseRequest(Request.Method.GET, "http://example.com/test.php",
            new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {
                    // This is status code: response.statusCode
                    // This is string response: NetworkResponseRequest.parseToString(response)
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }
    );

It is not nice to use my own implementation instead of StringRequest. What do you think about it ?