首页 > 解决方案 > 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);

标签: javarestweb-servicescharacter-encoding

解决方案


Manage to use below to solve my issue. post.addHeader("Content-type", "application/json; charset=UTF-8"); post.addHeader("Accept", "application/json");


推荐阅读