java - POST request body cannot contain chinese characters in Java
问题描述
I am using Hibernate and GSON to retrieve data as an object in Java, and create a .toString
method via GSON in the POJO to make JSON string. Now I need to use this JSON as a request body to send a POST request to a web service.
The problem is that if the JSON contains any chinese character, it will not work. It complains the chinese name field is incorrect. I checked and there are no spaces in the chinese string, and the .length()
of that is exactly the number of characters.
I also tried to copy the whole JSON and paste it to Postman to make the POST request. It will work. How come it does not work in my Java code but works in Postman? Below is how I create the POST request.
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_TIMEOUT)
.setConnectTimeout(CONNECTION_TIMEOUT)
.setSocketTimeout(CONNECTION_TIMEOUT)
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
StringBuilder entity = new StringBuilder();
entity.append(myJsonFromPojo);
HttpPost post = new HttpPost(uri);
post.addHeader("content-type", "application/json");
post.addHeader("Content-Type", "charset=UTF-8");
post.addHeader("Accept", "*/*");
post.addHeader("Accept-Encoding", "gzip,deflate");
post.addHeader("Authorization", "Bearer " + token);
post.setEntity(new StringEntity(entity.toString()));
response = httpClient.execute(post);
解决方案
Manage to use below to solve my issue. post.addHeader("Content-type", "application/json; charset=UTF-8"); post.addHeader("Accept", "application/json");
推荐阅读
- python - 显示位于数据库 Django 2.2 中的图像
- python - 在 Python 中查找字典字典
- google-data-studio - 是否可以将记分卡结果引用到另一个记分卡中?
- javascript - 如何跨组件转移孩子?
- ios - 捕获视图的某个部分而不是整个视图
- c# - 在邮箱(草稿文件夹)的 Outlook Web 中使用 IMAP 附加/上传电子邮件时出现问题
- python - Python:用括号比较和替换 list[i]
- javascript - 将文件从服务器发送到客户端时尝试下载 excel(.xlsx) 时出现损坏的文件
- python - 在 salt 中安装软件包时是否可以使用“if”语句
- python - pyder 在运行时无法检测到新更改的代码