說明:現在很多網站都會在回傳數據的時候進行GZIP壓縮,我們可以在請求頭中申明支持GZIP壓縮。可以減輕網絡傳輸壓力,Xutils中已經實現。
下面是一個DEMO,便於理解。
private void initGzip() { findViewById(R.id.btn1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { boolean isGzip = false; // 初始化httpClient對象 DefaultHttpClient httpClient = new DefaultHttpClient(); // 初始化httpGe對象 HttpGet get = new HttpGet("http://mobileif.maizuo.com/city"); // 1.發送請求頭:`Accept-Encoding:gzip` get.addHeader("Accept-Encoding", "gzip"); // HttpGet get = new HttpGet("http://httpbin.org/gzip"); // 發起請求 HttpResponse response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() == 200) { // 2. 取的響應頭`Content-Encoding`,判斷是否包含Content-Encoding:gzip Header[] headers = response.getHeaders("Content-Encoding"); for (Header header : headers) { String value = header.getValue(); if (value.equals("gzip")) { isGzip = true; } } // 3.相應的解壓 String result; HttpEntity entity = response.getEntity(); if (isGzip) {// gzip解壓 InputStream in = entity.getContent(); GZIPInputStream gzipIn = new GZIPInputStream(in); // inputStream-->string result = convertStreamToString(gzipIn); } else {// 標准解壓 // 打印響應結果 result = EntityUtils.toString(entity); } System.out.println("result:" + result); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } }); } public static String convertStreamToString(InputStream is) throws IOException { try { if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8")); // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while ((line = reader.readLine()) != null) { // sb.append(line); sb.append(line).append("\n"); } } finally { is.close(); } return sb.toString(); } else { return ""; } } catch (Exception e) { e.printStackTrace(); return ""; } }