HttpClient在傳參和返回結果的中文亂碼問題


  我實例化一個StringEntiry,將json字符串寫入請求體中。然后無論我以哪種編碼方式輸出StringEntity中的content,其中的中文均為亂碼“???”。 這是怎么回事?

  總結:就是在傳遞的參數中設置,這個很重要

entity = new StringEntity(data,Charset.forName("UTF-8"));

  今天用httpclient傳輸json數據,服務端接受數據是中文亂碼,原來還覺得應該是服務端程序處理字符編碼的問題,后來用tcpdump抓包(tcpdump的相關內容可以參考:linux安裝tcpdump),發現送到服務端時的報文已經是亂碼,故可以百分百確定是我發送端的問題。

  經過分析驗證,最終解決問題,特在此記錄一下。

解決辦法:
  發送端進行設置編碼如下:

StringEntity s = new StringEntity(jsonStr, Charset.forName("UTF-8"));

  接收到響應的處理如下:

result = EntityUtils.toString(httpEntity, "UTF-8");// 返回json格式

完整代碼如下:

/**
 * post請求
 * @param url
 * @param json
 * @return
 */
public static String httpPost(String url, String jsonStr) {
    
    String result = null;
    // 創建HttpClientBuilder  
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
    // HttpClient  
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    try {
        RequestConfig config = null;
        if (StringUtils.isNotEmpty(Constants.PROXY_IP) && Constants.PROXY_PORT > 0) {
            // 依次是代理地址,代理端口號,協議類型
            String agreement = url.substring(0, url.indexOf(":"));
            HttpHost proxy = new HttpHost(Constants.PROXY_IP, Constants.PROXY_PORT, agreement);
            config = RequestConfig.custom().setProxy(proxy).build();
        }
        // 請求地址  
        HttpPost httpPost = new HttpPost(url);
        if(config != null) {
            httpPost.setConfig(config);
        }
        //設置請求的報文頭部的編碼
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        //httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=utf-8"));
        //設置期望服務端返回的編碼
        httpPost.setHeader("Accept", "appliction/json");
        //httpPost.setHeader(new BasicHeader("Accept", "application/json"));
        
        StringEntity s = new StringEntity(jsonStr, Charset.forName("UTF-8"));
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json;charset=utf-8");//發送json數據需要設置contentType
        httpPost.setEntity(s);
        //執行請求
        HttpResponse response = closeableHttpClient.execute(httpPost);
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
         //獲得響應的實體對象
            HttpEntity httpEntity = response.getEntity();
            if(httpEntity != null) {
             //使用Apache提供的工具類進行轉換成字符串
                result = EntityUtils.toString(httpEntity, "UTF-8");// 返回json格式
            }
        }
    }catch(Exception e) {
        logger.error("doPost請求異常,e:{}", e);
    }finally {
        // 釋放資源  
        try {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
        } catch (IOException e) {
            logger.error("關閉CloseableHttpClient異常,e:{}", e);
        } finally {
            closeableHttpClient = null;
        }
    }
    return result;
}

 

參考文章:https://blog.csdn.net/sdxushuxun/article/details/79282112

https://blog.csdn.net/xiaoyao8903/article/details/53244986/


免責聲明!

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



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