首页 > 解决方案 > JAVA中HttpClient请求的编码类型

问题描述

我有以下字符串,我将其传递给 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。

我的标题包含:“内容类型”:“应用程序/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());

        }

标签: javajsonhttpclient

解决方案


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

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

这进一步解释了W3C 国际化


推荐阅读