Search code examples
androidandroid-volleyretrofit2internal-server-error

Getting response code 200 in Postman but not on Android Network library


I have a POST method API which is giving 200 response code in Postman but not when calling api by using Volley or even in Retrofit2.

Here is Postman screenshots:

enter image description here

Here what i did for Volley library code:

final String url = "http://xxxxxxxx.com/api/mobile/user/post/";

    StringRequest stringReq = new StringRequest(Request.Method.POST, url,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.e("onResponse ===", response + " " );
                }
            },
            new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("onErrorResponse ===", error + " " );
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("Authorization", "xxxxxxxxxxxxx");
            return params;
        }

        @Override
        public Map<String, String> getParams() {
            HashMap<String, String> params = new HashMap<>();
            params.put("post_body", "test");
            return params;
        }
    };

    // Adding request to request queue
    mApp.addToRequestQueue(stringReq);
    stringReq.setRetryPolicy(new DefaultRetryPolicy(
            REQUEST_TIME,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Error Logcat:

BasicNetwork.performRequest: Unexpected response code 500 for http://xxxxxxxxxxx.com/api/mobile/user/post/

Solution

  • The problem is that your endpoint assumes multipart/form-data request (as orange pin is set to form-data radiobutton in Postman), while Volley's default content-type for StringRequest is application/x-www-form-urlencoded, that's why you get 500 error.

    So, if you're only supposed to send POST params in multipart request, check this answer. But if you want to send files as well, check another answer