HTTP協議上的GZIP編碼是一種用來改進WEB應用程式效能的技術。大流量的WEB網站常常使用GZIP壓縮技術來減少檔案大小,減少檔案大小有兩個明顯的好處,一是可以減少儲存空間,二是通過網路傳輸檔案時,可以減少傳輸的時間。作者在寫這篇部落格時經過測試,4.4MB的文本資料經過Gzip傳輸到用戶端之後變為392KB,壓縮效率極高。
一.服務端
服務端有2種方式去壓縮,一種可以自己壓縮,但是更推薦第二種方式,用PrintWriter作為輸出資料流,工具類代碼如下
/** * 判斷瀏覽器是否支援 gzip 壓縮 * @param req * @return boolean 值 */public static boolean isGzipSupport(HttpServletRequest req) {String headEncoding = req.getHeader("accept-encoding");if (headEncoding == null || (headEncoding.indexOf("gzip") == -1)) { // 用戶端 不支援 gzipreturn false;} else { // 支援 gzip 壓縮return true;}}/** * 建立 以 gzip 格式 輸出的 PrintWriter 對象,如果瀏覽器不支援 gzip 格式,則建立普通的 PrintWriter 對象, * @param req * @param resp * @return * @throws IOException */public static PrintWriter createGzipPw(HttpServletRequest req, HttpServletResponse resp) throws IOException {PrintWriter pw = null;if (isGzipSupport(req)) { // 支援 gzip 壓縮pw = new PrintWriter(new GZIPOutputStream(resp.getOutputStream()));// 在 header 中設定傳回型別為 gzipresp.setHeader("content-encoding", "gzip");} else { // // 用戶端 不支援 gzippw = resp.getWriter();}return pw;}
servlet代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setCharacterEncoding("utf-8");response.setHeader("Content-Encoding", "gzip");String ret = "{\"ContentLayer\":{\"title\":\"內容層\"},\"PageLink\":{\"title\":\"頁面跳轉\"},\"WebBrowser\":{\"title\":\"瀏覽器\"},"+ "\"InlinePage\":{\"title\":\"內嵌頁面\"},\"VideoComp\":{\"title\":\"視頻\"},"+ "\"PopButton\":{\"title\":\"內容開關\"},\"ZoomingPic\":{\"title\":\"縮放大圖\"},"+ "\"Rotate360\":{\"title\":\"360度旋轉\"}}";PrintWriter pw = new PrintWriter(new GZIPOutputStream(response.getOutputStream()));pw.write(ret);pw.close();}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}
在代理軟體中跟蹤到的資料如下:
«VrÎÏ+IÍ+ñI¬L-R²ªV*É,ÉIU²R:rëÄÝMjuÓS}2ó²e/m>üìÌë«@òáINEùåŨú¬?pàØw¼g^Nf^*ÈTóoRï[¬àÔåc[ÁÖç8äç¡»nÿª7@¢òós3óÒ2UþºýèÏg÷Tå$¤ +r·¸ðäZh¤
實際資料如下:
{"ContentLayer":{"title":"內容層"},"PageLink":{"title":"頁面跳轉"},"WebBrowser":{"title":"瀏覽器"},"InlinePage":{"title":"內嵌頁面"},"VideoComp":{"title":"視頻"},"PopButton":{"title":"內容開關"},"ZoomingPic":{"title":"縮放大圖"},"Rotate360":{"title":"360度旋轉"}}
二.Android用戶端
得到HttpClient代碼:
private static DefaultHttpClient getHttpClient() {DefaultHttpClient httpClient = new DefaultHttpClient();// 設定 連線逾時時間httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);// 設定 讀資料逾時時間httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,TIMEOUT_SOCKET);// 設定 字元集httpClient.getParams().setParameter("http.protocol.content-charset",UTF_8);return httpClient;}
得到HttpPost:
private static HttpPost getHttpPost(String url) {HttpPost httpPost = new HttpPost(url);// 設定 請求逾時時間httpPost.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,TIMEOUT_SOCKET);httpPost.setHeader("Connection", "Keep-Alive");httpPost.addHeader("Accept-Encoding", "gzip");return httpPost;}
訪問網路代碼:
public static InputStream http_post_return_byte(String url,Map<String, String> params) throws AppException {DefaultHttpClient httpclient = null;HttpPost post = null;HttpResponse response = null;StringBuilder sb = null;StringEntity stringEntity = null;try {httpclient = getHttpClient();post = getHttpPost(url);sb = new StringBuilder();if (params != null && !params.isEmpty()) {Logger.d("In http_post the url is get here");for (Entry<String, String> entry : params.entrySet()) {sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),HTTP.UTF_8)).append("&");}sb.deleteCharAt(sb.lastIndexOf("&"));Logger.d("In http_post the url is " + url + " and params is "+ sb.toString());stringEntity = new StringEntity(sb.toString());stringEntity.setContentType("application/x-www-form-urlencoded");post.setEntity(stringEntity);}response = httpclient.execute(post);int statusCode = response.getStatusLine().getStatusCode();Logger.d("statusCode is " + statusCode);if (statusCode != HttpStatus.SC_OK) {throw AppException.http(statusCode);}InputStream is = response.getEntity().getContent();Header contentEncoding = response.getFirstHeader("Content-Encoding");if (contentEncoding != null&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {is = new GZIPInputStream(new BufferedInputStream(is));}return is;} catch (ClientProtocolException e) {e.printStackTrace();throw AppException.http(e);} catch (IOException e) {e.printStackTrace();throw AppException.network(e);} finally {/* * if (!post.isAborted()) { * * post.abort(); } httpclient = null; */}}
轉載請標明出處http://blog.csdn.net/shimiso
歡迎有識之士加入我們的技術交流群:173711587