最近在做一个类似天气预报的demo,数据是从http://wthrcdn.etouch.cn/weather_mini?city=获取,但是解析出来的字符串是乱码,通常更换编码类型就可以了,但是并不见效。所以最后才发现问题所在,这个接口的数据传给客户端的时候把数据压缩了,所以当我们在客户端获取到数据后要给他解压缩gzip即可,问题就解决了,现在把代码贴出来。
// 获取天气预报
public void getWeatherByHttp(String city) {
String url = Constants.GETWEATHER;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("city", city));
String param = URLEncodedUtils.format(params, "utf-8");
HttpGet httpGet = new HttpGet(url + param);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
String result = getJsonStringFromGZIP(httpResponse);// 获取到解压缩之后的字符串
Log.i("result", result);
JSONObject obj = new JSONObject(result);
if (obj != null && obj.getString("desc").equals("OK")) {
String str = obj.getString("data");
WeatherModel model = new Gson().fromJson(str,
WeatherModel.class);
handler.sendMessage(handler
.obtainMessage(GETWEATHERDATA, model));
} else {
handler.sendMessage(handler.obtainMessage(GETWEATHERDATA,
obj.getString("desc")));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getJsonStringFromGZIP(HttpResponse response) {
String jsonString = null;
try {
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(2);
// 取前两个字节
byte[] header = new byte[2];
int result = bis.read(header);
// reset输入流到开始位置
bis.reset();
// 判断是否是GZIP格式
int headerData = getShort(header);
if (result != -1 && headerData == 0x1f8b) {
is = new GZIPInputStream(bis);
} else {
is = bis;
}
InputStreamReader reader = new InputStreamReader(is, "utf-8");
char[] data = new char[100];
int readSize;
StringBuffer sb = new StringBuffer();
while ((readSize = reader.read(data)) > 0) {
sb.append(data, 0, readSize);
}
jsonString = sb.toString();
bis.close();
reader.close();
} catch (Exception e) {
Log.e("HttpTask", e.toString(), e);
}
return jsonString;
}
private int getShort(byte[] data) {
return (int) ((data[0] << 8) | data[1] & 0xFF);
}