【发布时间】:2017-02-07 02:18:16
【问题描述】:
我有一个 web api 设置,API 中的一个端点采用 JSON 对象(在 API 中被解析为 .NET 对象)。
使用 Postman 我可以成功调用 post 端点,这里是 URL
https://example.com/api/helprequests
这是我在 Postman 请求中包含的 JSON
{"Title":"Test Title", "Message":"Test Message"}
在 Postman 中一切正常,但我正在尝试使用 Volley 从 Android 应用程序调用此 API。
这里是相关代码
String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, webAddress,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
@Override
public String getBodyContentType() {
return "application/json";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("Title","Test title");
params.put("Message", "Test message");
} catch (Exception ex) {
VolleyLog.wtf("Unsupported Encoding");
return null;
}
return null;
}
};
queue.add(stringRequest);
当我运行它时,我收到以下错误:
E/Volley: [50225] BasicNetwork.performRequest: Unexpected response code 500 for https://example.com/api/helprequests
如何将帖子数据添加到 Volley 请求?
【问题讨论】:
-
标题和消息是否应该在正文中而不是在标题中?此外,您在正文中返回 null。
-
我认为title和message应该在body里面——getBody的目的是什么?我从网上的多个地方把它放在一起
-
不要使用
getBody。你有 JSON。 Volley 有 JSON 类。 afzaln.com/volley/com/android/volley/toolbox/… -
无论如何,你有一个 500 错误,那么你的服务器说什么是错误的?
-
@andrewb 我可以看看你如何在邮递员中提出请求的截图吗?为了安全起见,只需隐藏您的网址即可。
标签: android json android-volley