Today I encountered a project that needs to use httpClient to remotely call webservice services. In this project, both the service end and the server end are used
The org.springframework.web.filter.CharacterEncodingFilter filter is used to set the encoding format of the data submitted by POST, but the Chinese data obtained by the server is still garbled.
The following is a method of the httpClient tool class I wrote:
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单,此时需要设置数据的编码格式,否则默认会以ISO_8859_1进行编码
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
If the encoding method is not specified in UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");, after checking the source code, it is found that iso-8859-1 will be used to encode the data by default, which is the cause of the garbled code.
Although this problem is solved, there is still a doubt. Why is it that the org.springframework.web.filter.CharacterEncodingFilter filter is used to encode the post data, but it still needs to be specified in httpCilent? If any master knows, please let me know! ! !