Viks
Viks

Reputation: 1574

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/

Upvotes: 2

Views: 7034

Answers (3)

himanshu kumar
himanshu kumar

Reputation: 11

I also had the same issue I solved by using

 @Override
 public Map<String, String> getHeaders() throws AuthFailureError {
  final Map<String, String> headers = new HashMap<>();
  headers.put("Content-Type", "application/json");
  return headers;
 }

Upvotes: -1

romtsn
romtsn

Reputation: 11982

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

Upvotes: 7

Hemanth S
Hemanth S

Reputation: 688

Why don't you use JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, JSONObject, response, error); for post request it's easy to use try once

Upvotes: 0

Related Questions