在 Postman 中获取响应代码 200,但在 Android 网络库上未获取响应代码

2024-03-21

我有一个 POST 方法 API,它给出了 200 个响应代码Postman但在使用调用 api 时则不然Volley甚至在改造2.

这是邮递员截图:

这是我所做的Volley库代码:

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/

问题是你的端点假设multipart/form-data请求(橙色引脚设置为form-data邮递员中的单选按钮),而Volley的默认内容类型StringRequest is application/x-www-form-urlencoded,这就是您收到 500 错误的原因。

因此,如果您只想在多部分请求中发送 POST 参数,请检查这个答案 https://stackoverflow.com/a/38238994/3225458。但如果您也想发送文件,请检查另一个答案 https://stackoverflow.com/a/16803473/3225458

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Postman 中获取响应代码 200,但在 Android 网络库上未获取响应代码 的相关文章