我有一个 POST 方法 API,它在 Postman 中给出 200 响应代码,但在使用 Volley 或什至在 Retrofit2 中调用 api 时却没有.
这是 Postman 截图:
这是我为 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));
错误 Logcat:
BasicNetwork.performRequest: Unexpected response code 500 for http://xxxxxxxxxxx.com/api/mobile/user/post/
最佳答案
问题是您的端点假定 multipart/form-data
请求(因为橙色 pin 在 Postman 中设置为 form-data
radiobutton),而 Volley
的 StringRequest
默认内容类型是 application/x-www-form-urlencoded
,这就是您收到 500 错误的原因。
因此,如果您只应该在多部分请求中发送 POST 参数,请检查 this answer .但是如果你也想发送文件,检查another answer
关于android - 在 Postman 中获取响应代码 200 而不是在 Android 网络库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935546/