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)
那么没问题,但只查询支持字符串。
最佳答案
简短回答:如果您使用form()
,您将无法更改请求的内容类型和内容长度。它是一种特殊的方法,用于在正文中发送编码为多部分或 url 编码方式的参数。这只是 HTTP 的规范:) 通过更改内容类型,您的服务器将收到不正确的请求:它需要 json 正文,而不是表单参数。
您可以通过两种方式解决此问题:
- 要么encode输入 JSON 并将其设置为
bodyText()
并使用application/json
内容类型;或 - 不要尝试更改内容类型并使用
表单
。
如果您能解释为什么当此请求中不涉及 json 时需要将 content-type 的默认值更改为 JSON,将会很有帮助?
关于java - jodd HttpRequest 表单设置的内容类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298937/