我在做天气预报程序的时候遇到的问题,我通过 android 里面 HttpUrlConnection 连接到 http://wthrcdn.etouch.cn/weather_mini?city=北京 这个网址,可以根据城市名查询天气信息,它返回的是一个 json 字符串,但是网上说这个网址返回的 json 字符串是被压缩过的,因此要自己解析,我用 GZIPInputStream 去解压缩,在 java 里面可以正常打印出结果,代码和结果如下:
new Thread(new Runnable() {
private boolean isGZip = true;
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://wthrcdn.etouch.cn/weather_mini?city=芜湖");
//URL url = new URL("http://www.weather.com.cn/data/list3/city.xml");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
String response = "";
if (connection.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
InputStream is = connection.getInputStream(); // 获取输入流
System.out.println(connection.getContentEncoding());
if (isGZip ) {
//InflaterInputStream ilis = new InflaterInputStream(is);
GZIPInputStream in = new GZIPInputStream(is);
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "utf-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response += line;
}
} else {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "utf-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response += line;
}
}
}
System.out.println(response);
} catch (Exception e) {
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
运行结果是这样的:
gzip
{"desc":"OK","status":1000,"data":{"wendu":"26","ganmao":"相对于今天将会出现大幅度降温,空气湿度较大,易发生感冒,请注意适当增加衣服。","forecast":[{"fengxiang":"北风","fengli":"3-4级","high":"高温 28","type":"中雨","low":"低温 26","date":"9日星期天"},{"fengxiang":"北风","fengli":"微风级","high":"高温 29","type":"大雨","low":"低温 25","date":"10日星期一"},{"fengxiang":"北风","fengli":"微风级","high":"高温 28","type":"小雨","low":"低温 24","date":"11日星期二"},{"fengxiang":"西北风","fengli":"3-4级","high":"高温 27","type":"多云","low":"低温 23","date":"12日星期三"},{"fengxiang":"东风","fengli":"微风级","high":"高温 30","type":"多云","low":"低温 23","date":"13日星期四"}],"yesterday":{"fl":"4-5级","fx":"东风","high":"高温 32","type":"雷阵雨","low":"低温 27","date":"8日星期六"},"city":"芜湖"}}
可是,这完全相同的程序放在 android 里面执行时,我跟踪到 GZIPInputStream in = new GZIPInputStream(is); 这一句时,程序抛异常,直接走 catch 中的代码了,异常是 java.io.IOException: unknown format (magic number 227b),搞了好久了都解决不了,求大神帮忙解决!不胜感激
1
ss098 2015-08-09 18:18:59 +08:00
本例压缩过的含义是去除了换行符以及多余的空格,而不是 GZip。
|
3
ss098 2015-08-09 19:05:34 +08:00
@creatorYC 我不懂 Java,通常 HTTP 库已经帮你处理好了 GZip 以及相关的网络问题,所以只需要调用 JSON 解析库去解析这个字符串。
|
4
ss098 2015-08-09 19:07:56 +08:00
|
5
hahasong 2015-08-09 19:15:09 +08:00
http://stackoverflow.com/questions/16442516/android-httpurlconnection-gzip-compression
去掉Gzip条件,HttpURLConnection应该自动帮你处理了 |