【问题标题】:Encoding type of HttpClient request in JAVAJAVA中HttpClient请求的编码类型
【发布时间】:2019-06-21 10:16:32
【问题描述】:

我将以下字符串传递给 http-post-request:

字符串主体 =

{
  "invoicee": {
    "customer": {
      "type": "company",
      "id": "a62117d6-d324-0ae8-8f69-bb63ada0fee2"
    }
  },
  "department_id": "fba7d16b-a988-0420-894f-444b033ac379",
  "payment_term": {
    "type": "cash"
  },
  "grouped_lines": [
    {
      "section": {
        "title": ""
      },
      "line_items": [
        {
          "quantity": 3,
          "description": "An awesome product",
          "unit_price": {
            "amount": 123.3,
            "currency": "EUR",
            "tax": "excluding"
          },
          "tax_rate_id": "23d7af10-427b-06e4-8242-88e8228cc381"
        }
      ]
    }
  ],
  "custom_fields": [
    {
      "id": "673bfdeb-1112-0423-9e54-a8adace28ae4",
      "value": "Opdrachtbon Kruidvat 8957 365690.01 Kruidvat 8957 Neerstraat 34 Brakel (OVL) De keukenkraan is eraf gevallen, robinet cuisine est tombé "
    }
  ]
}
        headers.add("Content-Type", "application/json");

        headers.add("authorization", "Bearer " + acces_token);

它返回了一个 400 错误请求,其中包含特定信息表明这是一个格式错误的 JSON。

我的标题包含:“Content-type”:“application/json”。

问题出在 custom_fields 对象中,在“值”中有以下字符“é”。用 'e' 替换这个字符使 json 正常,我的响应状态为 201 OK。

您知道我可以如何在以后的请求中防止这种情况发生吗?我必须为我的请求输入特定的编码吗?

ATM 我的请求如下所示:

        HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);

        try {
            rest.exchange("https://api.teamleader.eu/invoices.draft", HttpMethod.POST, requestEntity, String.class);
        } catch (HttpClientErrorException e) {
            System.out.println("!!ERROR!!");
            System.out.println(e.getResponseBodyAsString());

        }

【问题讨论】:

  • 你的 JSON 没问题。 body 到底是什么,requestEntity 中的 headers 是什么?
  • 见上面的编辑。

标签: java json httpclient


【解决方案1】:

您可能需要在标题中设置字符集

内容类型:应用程序/json;字符集=utf-8

这进一步解释了W3C Internationalisation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多