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

三世轮回 提交于 2020-01-24 13:07:45

问题


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:

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/

回答1:


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




回答2:


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




回答3:


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;
 }


来源:https://stackoverflow.com/questions/41935546/getting-response-code-200-in-postman-but-not-on-android-network-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!