Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get network response even status code not 200

I using API for login, if login success it return code 200 with respone. and if incorrect email or password will return code 401 with json object contain errors the problem is that I want to get the network response even the request code not equal 200 like the image postman response

but volley throw exception BasicNetwork.performRequest: Unexpected response code 401

here is my code

public interface OnResponse{
    void onResponse(JSONObject response) throws Exception;
    void onErrorResponse(VolleyError volleyError);
}//OnResponse



public static void newRequest(Context context, String url, final Map<String, String>params, final OnResponse onResponse){
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    RequestQueue queue = Volley.newRequestQueue(context);
    //
    //onErrorResponse()
    //onResponse()
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
        // - - - - - - - - - - - - - - - - - - - - -
        try {
            JSONObject object = new JSONObject(response);
            onResponse.onResponse(object);
        } catch (Exception e) {
            Log.e(TAG, "FLAG-1");
            e.printStackTrace();
        }
        // - - - - - - - - - - - - - - - - - - - - -
    }, error -> {
        Log.e(TAG, "FLAG-2");
        onResponse.onErrorResponse(error);
    }){
        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            volleyError.printStackTrace();
            Log.e("zxc", volleyError.getMessage()+"");
            Log.e("zxc", volleyError.getLocalizedMessage()+"");
            return super.parseNetworkError(volleyError);
        }
    };
    //
    stringRequest.setParams(params);
    stringRequest.setShouldCache(false);
    queue.add(stringRequest);
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}//newRequest()`
like image 703
Ahmed M. Abdalla Avatar asked Dec 20 '25 21:12

Ahmed M. Abdalla


1 Answers

VolleyError has the networkResponse attribute, it contains the response.

This is an example: String response = new String(error.networkResponse.data);

like image 102
Salvatore Cozzubo Avatar answered Dec 23 '25 12:12

Salvatore Cozzubo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!