jodd HttpRequest 表单设置的内容类型无效
jodd HttpRequest form set content-type invalid
HttpRequest 设置表单内容类型无效
@Test
public void getImgCode() {
Map<String, Object> param = new HashMap<>();
param.put("userId", "11111");
HttpRequest request = HttpRequest.post(baseUrl + "openapi/api/v2/getCode")
.header("content-type","application/json;charset=utf-8")
.form(param);
System.out.println(request.contentType());
HttpResponse response = request.send();
System.out.println(response.bodyText());
}
but print content-type = application/x-www-form-urlencoded;charset=utf-8
如果使用httpQequest.query(param)
那么没问题,但查询只支持String。
简短回答:如果您使用 form()
,则您无法更改请求的内容类型和内容长度。它是一种用于在正文中发送编码为多部分或 url 编码方式的参数的特殊方法。这只是 HTTP 的规范 :) 通过更改内容类型,您的服务器将收到不正确的请求:它期望 json 正文,而不是表单参数。
您可以通过两种方式解决这个问题:
- 要么 encode 您对 JSON 的输入并将其设置为
bodyText()
并使用 application/json
内容类型;或
- 不要尝试更改内容类型并使用
form
。
如果您能解释为什么需要将 content-type 的默认值更改为 JSON,而没有 json 参与此请求,这将很有帮助?
HttpRequest 设置表单内容类型无效
@Test
public void getImgCode() {
Map<String, Object> param = new HashMap<>();
param.put("userId", "11111");
HttpRequest request = HttpRequest.post(baseUrl + "openapi/api/v2/getCode")
.header("content-type","application/json;charset=utf-8")
.form(param);
System.out.println(request.contentType());
HttpResponse response = request.send();
System.out.println(response.bodyText());
}
but print content-type = application/x-www-form-urlencoded;charset=utf-8
如果使用httpQequest.query(param)
那么没问题,但查询只支持String。
简短回答:如果您使用 form()
,则您无法更改请求的内容类型和内容长度。它是一种用于在正文中发送编码为多部分或 url 编码方式的参数的特殊方法。这只是 HTTP 的规范 :) 通过更改内容类型,您的服务器将收到不正确的请求:它期望 json 正文,而不是表单参数。
您可以通过两种方式解决这个问题:
- 要么 encode 您对 JSON 的输入并将其设置为
bodyText()
并使用application/json
内容类型;或 - 不要尝试更改内容类型并使用
form
。
如果您能解释为什么需要将 content-type 的默认值更改为 JSON,而没有 json 参与此请求,这将很有帮助?