android GZIP傳輸

HTTP協議上的GZIP編碼是一種用來改進WEB應用程序性能的技術。大流量的WEB站點經常使用GZIP壓縮技術來減小文件大小,減小文件大小有兩個明顯的好處,一是能夠減小存儲空間,二是經過網絡傳輸文件時,能夠減小傳輸的時間。做者在寫這篇博客時通過測試,4.4MB的文本數據通過Gzip傳輸到客戶端以後變爲392KB,壓縮效率極高。html

一.服務端

服務端有2種方式去壓縮,一種能夠本身壓縮,可是更推薦第二種方式,用PrintWriter做爲輸出流,工具類代碼以下java

[java] view plaincopy瀏覽器

  1. /** 網絡

  2.          * 判斷瀏覽器是否支持 gzip 壓縮 app

  3.          * @param req ide

  4.          * @return boolean 值 工具

  5.          */  post

  6.         public static boolean isGzipSupport(HttpServletRequest req) {  性能

  7.             String headEncoding = req.getHeader("accept-encoding");  測試

  8.             if (headEncoding == null || (headEncoding.indexOf("gzip") == -1)) { // 客戶端 不支持 gzip  

  9.                 return false;  

  10.             } else { // 支持 gzip 壓縮  

  11.                 return true;  

  12.             }  

  13.         }  

  14.   

  15.         /** 

  16.          * 建立 以 gzip 格式 輸出的 PrintWriter 對象,若是瀏覽器不支持 gzip 格式,則建立普通的 PrintWriter 對象, 

  17.          * @param req 

  18.          * @param resp 

  19.          * @return  

  20.          * @throws IOException 

  21.          */  

  22.         public static PrintWriter createGzipPw(HttpServletRequest req, HttpServletResponse resp) throws IOException {  

  23.             PrintWriter pw = null;  

  24.             if (isGzipSupport(req)) { // 支持 gzip 壓縮  

  25.                 pw = new PrintWriter(new GZIPOutputStream(resp.getOutputStream()));  

  26.                 // 在 header 中設置返回類型爲 gzip  

  27.                 resp.setHeader("content-encoding""gzip");  

  28.             } else { // // 客戶端 不支持 gzip  

  29.                 pw = resp.getWriter();  

  30.             }  

  31.             return pw;  

  32.         }  

  33.       

servlet代碼以下:

[java] view plaincopy

  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  

  2.         throws ServletException, IOException {  

  3.     response.setCharacterEncoding("utf-8");  

  4.     response.setHeader("Content-Encoding""gzip");  

  5.     String ret = "{\"ContentLayer\":{\"title\":\"內容層\"},\"PageLink\":{\"title\":\"頁面跳轉\"},\"WebBrowser\":{\"title\":\"瀏覽器\"},"  

  6.             + "\"InlinePage\":{\"title\":\"內嵌頁面\"},\"VideoComp\":{\"title\":\"視頻\"},"  

  7.             + "\"PopButton\":{\"title\":\"內容開關\"},\"ZoomingPic\":{\"title\":\"縮放大圖\"},"  

  8.             + "\"Rotate360\":{\"title\":\"360度旋轉\"}}";  

  9.       

  10.     PrintWriter pw = new PrintWriter(new GZIPOutputStream(response.getOutputStream()));  

  11.     pw.write(ret);  

  12.     pw.close();  

  13. }  

  14.   

  15. public void doGet(HttpServletRequest request, HttpServletResponse response)  

  16.         throws ServletException, IOException {  

  17.     this.doPost(request, response);  

  18. }  

在代理軟件中跟蹤到的數據以下:

[html] view plaincopy

  1. ‹«VrÎÏ+IÍ+ñI¬L-R²ªV*É,ÉIU²R:rëÄÝM•ju” ÓS}2ó²‘e/m>üì̏ë«@òá©INEùåŨúŸ¬?pàØw¼g^Nf^*È Tóo ™ R –™’šïœŸ[€¬àÔåc[ÁÖç 8•–”äç¡»nÿª7@  

  2. ¢òós3óÒ 2“‘Uœþºýè–Ïg÷€T å—$–¤ ›  +r·¸ð ä‡Zh¤†ˆ  


實際數據以下:

[html] view plaincopy

  1. {"ContentLayer":{"title":"內容層"},"PageLink":{"title":"頁面跳轉"},"WebBrowser":{"title":"瀏覽器"},"InlinePage":{"title":"內嵌頁面"},"VideoComp":{"title":"視頻"},"PopButton":{"title":"內容開關"},"ZoomingPic":{"title":"縮放大圖"},"Rotate360":{"title":"360度旋轉"}}  


二.Android客戶端

獲得HttpClient代碼:

[html] view plaincopy

  1. private static DefaultHttpClient getHttpClient() {  

  2.         DefaultHttpClient httpClient = new DefaultHttpClient();  

  3.   

  4.         // 設置 鏈接超時時間  

  5.         httpClient.getParams().setParameter(  

  6.                 HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);  

  7.         // 設置 讀數據超時時間  

  8.         httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,  

  9.                 TIMEOUT_SOCKET);  

  10.         // 設置 字符集  

  11.         httpClient.getParams().setParameter("http.protocol.content-charset",  

  12.                 UTF_8);  

  13.         return httpClient;  

  14.     }  


獲得HttpPost:

[java] view plaincopy

  1. private static HttpPost getHttpPost(String url) {  

  2.         HttpPost httpPost = new HttpPost(url);  

  3.         // 設置 請求超時時間  

  4.         httpPost.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,  

  5.                 TIMEOUT_SOCKET);  

  6.         httpPost.setHeader("Connection""Keep-Alive");  

  7.         httpPost.addHeader("Accept-Encoding""gzip");  

  8.         return httpPost;  

  9.     }  


訪問網絡代碼:

[java] view plaincopy

  1. public static InputStream http_post_return_byte(String url,  

  2.             Map<String, String> params) throws AppException {  

  3.         DefaultHttpClient httpclient = null;  

  4.         HttpPost post = null;  

  5.         HttpResponse response = null;  

  6.         StringBuilder sb = null;  

  7.         StringEntity stringEntity = null;  

  8.         try {  

  9.             httpclient = getHttpClient();  

  10.             post = getHttpPost(url);  

  11.             sb = new StringBuilder();  

  12.             if (params != null && !params.isEmpty()) {  

  13.                 Logger.d("In http_post the url is get here");  

  14.                 for (Entry<String, String> entry : params.entrySet()) {  

  15.                     sb.append(entry.getKey())  

  16.                             .append("=")  

  17.                             .append(URLEncoder.encode(entry.getValue(),  

  18.                                     HTTP.UTF_8)).append("&");  

  19.                 }  

  20.                 sb.deleteCharAt(sb.lastIndexOf("&"));  

  21.                 Logger.d("In http_post the url is " + url + " and params is "  

  22.                         + sb.toString());  

  23.                 stringEntity = new StringEntity(sb.toString());  

  24.                 stringEntity  

  25.                         .setContentType("application/x-www-form-urlencoded");  

  26.                 post.setEntity(stringEntity);  

  27.             }  

  28.   

  29.             response = httpclient.execute(post);  

  30.             int statusCode = response.getStatusLine().getStatusCode();  

  31.             Logger.d("statusCode is " + statusCode);  

  32.             if (statusCode != HttpStatus.SC_OK) {  

  33.                 throw AppException.http(statusCode);  

  34.             }  

  35.   

  36.             InputStream is = response.getEntity().getContent();  

  37.   

  38.             Header contentEncoding = response  

  39.                     .getFirstHeader("Content-Encoding");  

  40.             if (contentEncoding != null  

  41.                     && contentEncoding.getValue().equalsIgnoreCase("gzip")) {  

  42.                 is = new GZIPInputStream(new BufferedInputStream(is));  

  43.             }  

  44.             return is;  

  45.   

  46.         } catch (ClientProtocolException e) {  

  47.             e.printStackTrace();  

  48.             throw AppException.http(e);  

  49.         } catch (IOException e) {  

  50.             e.printStackTrace();  

  51.             throw AppException.network(e);  

  52.         } finally {  

  53.   

  54.             /* 

  55.              * if (!post.isAborted()) { 

  56.              *  

  57.              * post.abort(); } httpclient = null; 

  58.              */  

  59.   

  60.         }  

  61.   

  62.     }  

相關文章
相關標籤/搜索