gpt4 book ai didi

android - 使用 Volley 在 POST 请求中发送数组的正确方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 14:43:49 25 4
gpt4 key购买 nike

当我使用 Postman 时,我使用下面的请求描述从服务器获得正确的响应(服务器将“类别”作为数组处理): Postman request body

带标题: Postman request headers

这个请求有这个原始表示:

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 中缺少一些微妙的配置以正确执行此类请求。

最佳答案

我承认问题中描述的问题主要是基于服务器的逻辑。通过转储来自 Volley 和 OkHttp 的请求主体并逐步比较它们,我可以发现它们仅在一个 header - Content-Type 上有所不同。在 OkHttp 中它看起来像:

Content-Type: application/x-www-form-urlencoded; charset=utf-8

在 Volley 中是:

Content-Type: application/x-www-form-urlencoded, application/x-www-form-urlencoded; charset=UTF-8

所以看起来这是对服务器上 header 的一种严格检查。为了使 Volley 的 header 与 OkHttp 的 header 相同,我必须在请求中删除对 getHeaders() 方法的覆盖,并在 getBodyContentType() 方法中返回正文类型描述:

@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}

我不能说我的问题已经完全解决了,因为关于如何使用更优雅的方式(没有原始主体和其他格式 - 例如 JSON)在 POST 请求主体中添加数组仍然可以有更多答案。

关于android - 使用 Volley 在 POST 请求中发送数组的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43270880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com