0

How to parse 401 response data for volley,here is the server response am getting i haev used volley network response but its not able to get response data which is in JSON format

Status 200 OK 
{
    alert: {
        title: "Unauthorised access to appointment"
        message: ""
    }-
    response: "0"
}



new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Req Failed!");
        mProgressDialog.dismiss();
        NetworkResponse localNetworkResponse = error.networkResponse;
        if (localNetworkResponse != null) {
            if (!WebAPIEngine.checkStatusCodeVolley(localNetworkResponse.statusCode)) {
                AlertDialogUtil.displayErrorAlert(error.toString(), mContext);
            }
        } else {
            Log.e(TAG, error.toString());
            try {
                JSONObject jsonObject = new JSONObject(error.getMessage());
                    if (WebAPIEngine.processErrorAlertResp(jsonObject)) {
                        AlertDialogUtil.displayErrorAlert(WebAPIEngine.getErrorMessage(), mContext);
                    } else {
                        AlertDialogUtil.displayErrorAlert(error.toString(), mContext);
                    }
                } 
            catch (Exception e) { e.printStackTrace(); }
        }
    }
});
sschrass
  • 7,014
  • 6
  • 43
  • 62
kondal
  • 358
  • 1
  • 6
  • 22
  • Have you tried parsing `JSONObject object = new JSONObject(new String(error.networkResponse.data));`? – Denis Loh Nov 14 '14 at 10:19
  • error.networkResponse am getting null – kondal Nov 14 '14 at 11:40
  • check first if the `error` is an instance of `NoConnectionError` or any other error type which does not contain a networkResponse. In the other case, networkResponse should be set and also should contain the expected data. – Denis Loh Nov 14 '14 at 11:50

2 Answers2

1

You can use the following code to get response

String responseString="";
if (networkResponse != null) {
    try {
        Log.v(TAG , ".getResponseError code :"+networkResponse.statusCode);
        responseString = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
        Log.v(TAG, ".getResponseError body :" + responseString);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

Also, beware 401 errors are unreliable to handle in Volley: The SO answer explains it perfectly.

Community
  • 1
  • 1
Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89
1

UPDATE July 2016

As mentioned, 401 errors are unreliable to handle in Volley but I recently found a workaround not mentioned in The S.O answer and I thought it could be useful if the provided solutions does not suit your case.

1) Create a base request extending any volley request (StringRequest, JSONObjectRequest, etc...) and override parseNetworkError() function

/* Custom volley request. I chose to extend JsonObjectRequest
 * feel free to extend any other volley class
 */ 
public class CundinasRequest extends JsonObjectRequest{
...
  @Override
  //This will make the volley error message to contain your server's error message
  protected VolleyError parseNetworkError(VolleyError volleyError) {
      if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
          volleyError = new VolleyError(new String(volleyError.networkResponse.data));
      }
      return volleyError;
  }
...
}

2) In your onErrorResponse() implementation you just have to parse your server's error. Here's an example:

//Volley request is made somewhere in this activity
public class MainActivity extends Activity {
  private final String AUTH_ERROR_IDENTIFIER = "invalid_token";
...
  public isAuthorizationError(VolleyError error){
    return error.getMessage().contains(AUTH_ERROR_IDENTIFIER); 
  }

  @Override
    public void onErrorResponse(VolleyError error) {
      if(isAuthorizationError(error)
        Log.e(TAG, "Please log in again");
  }

}      

I found this workaround useful as I couldn't change the server's return status and the authorization error was always the same. To give you an idea, it looked something like this:

{
  "error": "invalid_token",
  "error_description": "Invalid access token: AN INVALID TOKEN"
}
Carlos R.
  • 251
  • 3
  • 8