由于接收的数据经过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会出现问题。
浙公网安备 33010602011771号