The next version of the Project will provide support for gzip in order to faster speed of data transmission on the network。在我們的項目中,添加對gzip的支援,是為了加快資料在網路中的傳輸速度。
If you need to transfer data using gzip, you must be setting request header "Accept-Encoding"="gzip". Thus, you will get a response, which include the response header name "Content-Encoding" and value "gzip", and need to ungzip the response data. Besides,
the response header name "Content-Length" also will be returned.使用gzip,首先要佈建要求訊息頭Accept-Encoding為gzip。這樣,你將會得到一個響應,根據訊息頭Content-Encoding為gzip你可以知道,傳輸過來的資料是經過gzip壓縮的。另外,訊息頭Content-Length會告訴你壓縮後的資料長度。
A example using gzip implemented by Java。用Java實現的gzip
GetMethod method = new GetMethod(url);//產生一個get方法執行個體 method.setQueryString(queryString);//設定查詢字串 method.addRequestHeader("Accept-Encoding", "gzip");//設定接受響應訊息為gzip HttpClient client = new HttpClient();//產生執行get方法的用戶端執行個體 client.executeMethod(method);//執行get方法 InputStream in = method.getResponseBodyAsStream();//擷取響應訊息體 Header contentEncoding = method.getResponseHeader("Content-Encoding");//擷取訊息頭Content-Encoding判斷資料流是否gzip壓縮過 if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { GZIPInputStream gzipIn = new GZIPInputStream(in); int len = Integer.parseInt(method.getResponseHeader("Content-Length").getValue()); byte[] b = new byte[len]; gzipIn.read(b); String json = new String(b); System.out.println(json); }
In addtional, give a example about Server compress the data using gzip。使用gzip在伺服器端壓縮資料的例子。
byte[] result = data.getBytes("UTF-8"); if(response.getHeader("Accept-Encoding").equalsIgnoreCase("gzip")) { // System.out.println("Before compression, the data size is :"+ result.length); // Using gzip compress the data ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gout = new GZIPOutputStream(out); gout.write(json.getBytes("UTF-8")); gout.close(); result = out.toByteArray(); // System.out.println("After compression, the data size is "+gzipResult.length); this.getResp().setHeader("Content-Encoding","gzip"); this.getResp().setHeader("Content-Length", result.length+""); } response.getOutputStream().write(result);