码迷,mamicode.com
首页 > Web开发 > 详细

httpclient工具类,post请求发送json字符串参数,中文乱码处理

时间:2019-05-06 11:55:17      阅读:355      评论:0      收藏:0      [点我收藏+]

标签:ase   alt   mamicode   utils   .com   client   entity   mon   解决办法   

在使用httpclient发送post请求的时候,接收端中文乱码问题解决。

正文:

我们都知道,一般情况下使用post请求是不会出现中文乱码的。可是在使用httpclient发送post请求报文含中文的时候在发送端数据正常但是到了服务器端就中文乱码了。

解决办法:

发送端进行设置编码如下:

技术图片

 工具类:

 1 package com.Util;
 2 
 3 import com.google.common.base.Charsets;
 4 import org.apache.http.HttpEntity;
 5 import org.apache.http.client.methods.CloseableHttpResponse;
 6 import org.apache.http.client.methods.HttpPost;
 7 import org.apache.http.entity.StringEntity;
 8 import org.apache.http.impl.client.CloseableHttpClient;
 9 import org.apache.http.impl.client.HttpClients;
10 import org.apache.http.util.EntityUtils;
11 
12 public class HttpUtil {
13     public static String sendHttpPost(String url, String body) throws Exception {
14         CloseableHttpClient httpClient = HttpClients.createDefault();
15         HttpPost httpPost = new HttpPost(url);
16         httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
17         httpPost.setHeader("Accept", "application/json");
18         httpPost.setEntity(new StringEntity(body, Charsets.UTF_8));
19         CloseableHttpResponse response = httpClient.execute(httpPost);
20         System.out.println(response.getStatusLine().getStatusCode() + "\n");
21         HttpEntity entity = response.getEntity();
22         String responseContent = EntityUtils.toString(entity, "UTF-8");
23         response.close();
24         httpClient.close();
25         return responseContent;
26     }
27 
28 }

 

httpclient工具类,post请求发送json字符串参数,中文乱码处理

标签:ase   alt   mamicode   utils   .com   client   entity   mon   解决办法   

原文地址:https://www.cnblogs.com/newAndHui/p/10818601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!