CloseableHttpClient 调用 Post 的时候 StringEntity 字符集

在默认情况下 CloseableHttpClient 调用会使用 StringEntity 来设置字符串。

在设置好字符串后,我们会发送到远程 API 上进行执行。

比如说,我们可以先初始化 HttpPost 对象,然后设置 setEntity

HttpPost httpPost = new HttpPost("https://www.ossez.com/posts.json");
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");

下一步是初始化发送的 JSON 数据内容:

StringEntity postingString = new StringEntity(new Gson().toJson(topicRequest),  StandardCharsets.UTF_8);

然后将 JSON 数据内容设置到 HttpPost 实体中

httpPost.setEntity(postingString);

在这里有一个地方是需要注意的就是在设置 StringEntity 字符集的时候需要使用 UTF_8。

如果你不设置这个参数,默认是使用 ISO-8859-1 字符集的。

很多时候针对中文的环境都会使用到中文,ISO-8859-1 字符集是不能支持中文的,一般来说我们只要确保所有的发送数据都使用 UTF-8 就可以了。

https://www.ossez.com/t/closeablehttpclient-post-stringentity/8401

原文地址:https://www.cnblogs.com/huyuchengus/p/14290973.html