java – Get HTTP status code for successful requests with Volley-ThrowExceptions

Exception or error:

I’m retrieving the content of a invalid web address with volley, i.e. http://www.gigd32fdsu.com:
This is my test code:

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://www.gigd32fdsu.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
new Response.Listener() {
    @Override
    public void onResponse(Object response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: " + response.toString().substring(0, 500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work! " + error.networkResponse.statusCode);
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

When I run this code I receive the callback onResponse(String) with an error page from my ISP. How can I read the HTTP status code in order to detect that the web displaying is not correct?

Thanks

How to solve:

Simple solution is to override parseNetworkResponse in makeStringReq(), no need for another class:

private void makeStringReq() {
    showProgressDialog();

    StringRequest strReq = new StringRequest(Method.GET,
            Const.URL_STRING_REQ,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d(TAG, response.toString());
                    msgResponse.setText(response.toString());
                    hideProgressDialog();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hideProgressDialog();
                }
            }) {

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            int mStatusCode = response.statusCode;
            return super.parseNetworkResponse(response);
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

}

###

I will make the response from VinceStyling more complete. I’ll tell you what I do.

Once you override this method, save the statusCode in your class.

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            statusCode=response.statusCode;
            return super.parseNetworkResponse(response);
        }

After that you should compare it with HttpURLConnection constants to act accordingly. For example:

            int statusCode=webService.getStatusCode();
            switch (statusCode){
                case HttpURLConnection.HTTP_OK:
                    //do stuff
                    break;
                case HttpURLConnection.HTTP_NOT_FOUND:
                    //do stuff
                    break;
                case HttpURLConnection.HTTP_INTERNAL_ERROR:
                    //do stuff
                    break;
            }

###

Just override the parseNetworkResponse method then take the statusCode value.

public class StrImplRequest extends StringRequest {
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        // take the statusCode here.
        response.statusCode;
        return super.parseNetworkResponse(response);
    }
}

###

@VinceStyling ‘s answer is ok,
or you can extend Request class and do what you wanna do.
For example,

    ServerStatusRequestObject extends Request {

    private final Response.Listener mListener;
    private String mBody = "";
    private String mContentType;

    public ServerStatusRequestObject(int method,
                                     String url,
                                     Response.Listener listener,
                                     Response.ErrorListener errorListener) {

        super(method, url, errorListener);
        mListener = listener;
        mContentType = "application/json";

        if (method == Method.POST) {
            RetryPolicy policy = new DefaultRetryPolicy(5000, 0, 5);
            setRetryPolicy(policy);
        }
    }

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

    @Override
    protected void deliverResponse(Object response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        return mBody.getBytes();
    }

    @Override
    public String getBodyContentType() {
        return mContentType;
    }

    @Override
    public int compareTo(Object another) {
        return 0;
    }

then in your response handler, you can still receive the whole messages from server.
Try it.

Leave a Reply

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