httpclient工具類,post請求發送json字符串參數,中文亂碼處理


在使用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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM