我在做天气预报程序的时候遇到的问题,我通过 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),搞了好久了都解决不了,求大神帮忙解决!不胜感激
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.