
正文
httpclient工具类,post请求发送json字符串参数,中文乱码处理
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
在使用httpclient发送post请求的时候,接收端中文乱码问题解决。
正文:
我们都知道,一般情况下使用post请求是不会出现中文乱码的。可是在使用httpclient发送post请求报文含中文的时候在发送端数据正常但是到了服务器端就中文乱码了。
解决办法:
发送端进行设置编码如下:

工具类:
package com.Util; import com.google.common.base.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; public class HttpUtil {
public static String sendHttpPost(String url, String body) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(body, Charsets.UTF_8));
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode() + "\n");
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
return responseContent;
} }








