【发布时间】:2017-04-07 06:11:45
【问题描述】:
当我使用 Postman 时,我使用下面的请求描述从服务器获得正确的响应(服务器将“类别”作为数组处理):
此请求具有以下原始表示:
POST /api/items HTTP/1.1
Host: www1.
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: c18f92ee-2f36-f4dd-2963-6bc6d1db0bdf
items=247642&categories%5B%5D=12&categories%5B%5D=11
我的问题是如何使用 Volley 库来表示描述的请求以正确触发它。我尝试了很多变体,例如:
@Override
public byte[] getBody() throws AuthFailureError {
return "items=247642&categories%5B%5D=12".getBytes();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = super.getHeaders();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
但是它们要么不将“类别”编码为数组(所以服务器根本不考虑这个变量)或者以不正确的方式进行编码,所以服务器无法获取这个数组的值。
更新:
我刚刚尝试使用 OkHttp 触发这个请求,它是绝对正确的(就像上面的 Postman 一样):
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "items=247642&categories%5B%5D=10&categories%5B%5D=9");
Request request = new Request.Builder()
.url("http://www1...")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
这仅意味着一件事:Volley 以其他方式处理原始请求主体(可能是不正确的方式),或者 Volley 中缺少一些微妙的配置来正确执行此类请求。
【问题讨论】:
标签: android post request android-volley