【问题标题】:jodd HttpRequest form set content-type invalidjodd HttpRequest 表单设置的内容类型无效
【发布时间】:2017-07-25 09:17:13
【问题描述】:

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());
}

但是打印 content-type = application/x-www-form-urlencoded;charset=utf-8

如果使用httpQequest.query(param)那么没问题,但是只查询支持字符串。

【问题讨论】:

    标签: java httprequest jodd


    【解决方案1】:

    简短回答:如果您使用form(),您不能更改请求的内容类型和内容长度。它是一种特殊的方法,用于在正文中发送编码为多部分或 url 编码方式的参数。这只是 HTTP 的规范 :) 通过更改内容类型,您的服务器将收到不正确的请求:它需要 json 正文,而不是表单参数。

    您可以通过两种方式解决此问题:

    1. encode 输入到JSON 并将其设置为bodyText() 并使用application/json 内容类型;或
    2. 不要尝试更改内容类型并使用form

    如果您能解释为什么在此请求中不涉及 json 时需要将 content-type 的默认值更改为 JSON,将会很有帮助?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      相关资源
      最近更新 更多