請求天氣接口(http://wthrcdn.etouch.cn/weather_mini?citykey=101210101) 亂碼問題
public static String sendGet2(String url) throws IOException {
//實例化httpclient,(4.5新版本和以前不同),實例化方式有兩種
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:60.0) Gecko/20100101 Firefox/60.0");
CloseableHttpResponse response = null;
try {
/**
* 底層http鏈接仍由響應對象保存
* 允許直接從網絡套接字流式傳輸響應內容
* 為了確保正確釋放系統資源
* 用戶必須從finally子句中調用CloseableHttpResponse #close()
*/
response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
//對響應主體做一些有用的事情
//並確保他完全被消耗掉
String s = EntityUtils.toString(entity, "utf-8");
return s;
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
response.close();
}
}
即可解決該問題。