由於接收的數據經過gZip處理過,所以在接受的時候也要處理,並且加上編碼格式(沒有會出現部分數據亂碼):
具體代碼實現如下:
URL ul = new URL(url);
HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
StringBuffer sb = new StringBuffer();
String readLine = new String();
GZIPInputStream gZipS=new GZIPInputStream(in);
InputStreamReader res = new InputStreamReader(gZipS,"UTF-8");
BufferedReader responseReader = new BufferedReader(res);
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine);
}
responseReader.close();
測試問題解決。。
有一點需要補充的是:在使用gZip解壓數據的時候,記得關閉gZip:
String result = "";
GZIPInputStream gZipS = null;
try {
logger.debug("start getWeiboContent==url="+url);
StringBuffer sb = new StringBuffer();
String readLine = new String();
URL ul = new URL(url);
HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
conn.connect();
in = conn.getInputStream();
//解析八友數據
gZipS=new GZIPInputStream(in);
InputStreamReader res = new InputStreamReader(gZipS,"UTF-8");
BufferedReader responseReader = new BufferedReader(res);
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine);
}
result = sb.toString();
responseReader.close();
res.close();
gZipS.close();
in.close();
conn.disconnect();
logger.debug("end getWeiboContent==url="+url);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(gZipS!=null)
{
try {
gZipS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
gZipS.close();尤其重要,而且在一個流沒有關閉的時候再次操作新的gZip會出現問題。
