【Java】HttpClient 請求出現中文亂碼的問題

目錄

一、現象

二、解決方式

2.1 指定請求數據的字符集爲 utf-8 格式

2.2 通過 @RequestMapping 中的 produces 屬性解決,指定接收方的響應數據字符集爲 utf-8

三、原因和驗證

3.1 排除請求是否是亂碼

3.2 解決請求方獲取到響應的數據爲亂碼


一、現象

在測試 HttpClient 時出現中文亂碼的問題。但是在post請求的接收方中打印日誌,可以看到接收方收到的數據是正確的。

請求方的日誌:

接收方的日誌:

 

二、解決方式

先說解決方式:

2.1 指定請求數據的字符集爲 utf-8 格式

StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");

  

 

2.2 通過 @RequestMapping 中的 produces 屬性解決,指定接收方的響應數據字符集爲 utf-8

@RequestMapping(value = "/httpclient/postparm", produces = MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
.....

  

 

三、原因和驗證

出現中文亂碼的原因是由於沒有指定字符集爲 utf-8

3.1 排除請求是否是亂碼

先放上相關代碼:

@Test
public void doPostWithParam() throws Exception {
    // 創建一個httpclient對象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 創建一個post對象
    HttpPost post = new HttpPost("http://localhost:8083/httpclient/postparm.action");
    // 創建一個entity,模擬一個表單
    List<NameValuePair> kvList = new ArrayList<>();
    kvList.add(new BasicNameValuePair("name", "小王"));
    kvList.add(new BasicNameValuePair("pwd", "123456"));
    // 包裝成一個Entity對象
    StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
    // 設置請求的內容
    post.setEntity(entity);

    // 執行請求
    CloseableHttpResponse response = httpClient.execute(post);
    // 得到結果
    int statusCode = response.getStatusLine().getStatusCode();
    Log.info("status = " + statusCode);
    HttpEntity resEntity = response.getEntity();
    String str = EntityUtils.toString(resEntity);
    Log.info("str = " + str);
    // 關閉httpclient
    response.close();
    httpClient.close();
}

  

嘗試着去掉後再次請求:

  

  

可以得知由於在構造 entity 時已經指定了 utf-8 格式,故接收方拿到的數據不會亂碼

 

3.2 解決請求方獲取到響應的數據爲亂碼

我們可以猜測,是由於響應的數據字符集不是 utf-8 導致的。可以通過 @RequestMapping 中的 produces 屬性解決

@RequestMapping(value = "/httpclient/postparm", produces = MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
@ResponseBody
public String testPostParm(String name, String pwd) {
    Log.info("testPost   Parmname = " + name);
    Log.info("testPostParm    pwd = " + pwd);
    return "{username:" + name + ",pwd:" + pwd +"}";
}

重啓服務後再次訪問,問題解決了

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章