1. 程式人生 > >java Http請求亂碼 返回值gzip

java Http請求亂碼 返回值gzip

用java請求一個天氣介面,發現亂碼。
用chrome訪問亂碼,360極速正常顯示。
後來發現返回的gzip格式的
Content-Encoding:gzip

用java訪問時妥妥的亂碼就不用考慮是否解碼問題
不需要第三方jar包,匯入一個工具類就可以了

import java.util.zip.GZIPInputStream;

HttpClient httpClient = new DefaultHttpClient();
String url = "http://wthrcdn.etouch.cn/weather_mini?citykey=101070101"; // 天氣介面
HttpGet httpGet = new
HttpGet(url); HttpResponse response = httpClient.execute(httpGet); try { HttpEntity responsetEntity = response.getEntity(); InputStream inputStream = responsetEntity.getContent(); InputStream stream = new GZIPInputStream(inputStream); // 就加個這行就ok了 if(stream != null){ String data = IOUtils.toString(stream, "utf-8"
); // 返回值 } catch(Exception e){ }

讀取本地gz

String fileName = "C:\\Users\\Administrator\\Desktop\\doc\\test.txt.gz";
InputStream is = new GZIPInputStream(new FileInputStream(fileName));
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);