解決http://wthrcdn.etouch.cn/weather_mini?city=介面獲取天氣的返回字串是亂碼
阿新 • • 發佈:2019-02-05
最近在做一個類似天氣預報的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); }