標籤:httpservletresponse http 壓縮
我們在使用HttpServletRequest和HttpServletReonse等工具類的時候,這些工具類走的協議就是http協議,http協議也是我們日常WEB開發通用的協議。因為http協議封裝的很好,因此我們往往忽視了它,但是在對效能的極致追求中,這些基礎協議,又成為我們繼續努力的基礎。
響應,在http協議中有非常重要的作用。
可以設定Location回應標頭,實現請求重新導向(可以查看HttpServletRequest相關內容);也可以設定Content-Encoding回應標頭,告訴瀏覽器資料的壓縮格式;還可以設定content-type回應標頭,指定回送資料類型;也可以設定content-disposition回應標頭,讓瀏覽器下載檔案((可以查看HttpServletReonse相關內容))…
還可以利用它,做很多很多的事情。
1、WEB資料轉送中的壓縮(Content-Encoding)的原始碼
在頻寬不夠的時候,壓縮是一種解決事情的好方法;現在的頻寬是越來越大了,不過檔案也越來越大,壓縮還是有英雄用武之地的。其中百度等網站也是使用壓縮的資料傳遞方式。
package com.servlet;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*通過HttpServletResponse實現傳輸檔案的壓縮
*
*@author 範芳銘
*/
public class ResponseEncode extendsHttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException,IOException {
String data = "123456789012345678901234567890" +
"123456789012345678901234567890" +
"123456789012345678901234567890" +
"123456789012345678901234567890" +
"123456789012345678901234567890" +
"123456789012345678901234567890"+
"123456789012345678901234567890" +
"123456789012345678901234567890" +
"123456789012345678901234567890" +
"123456789012345678901234567890" ;
System.out.println("未經處理資料的大小為:" + data.getBytes().length);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
//能夠把檔案進行壓縮的對象
GZIPOutputStream gout = new GZIPOutputStream(bout); //buffer
gout.write(data.getBytes());
gout.close();
//得到壓縮後的資料
byte g[] = bout.toByteArray();
//告訴瀏覽器用gzip的方式解壓
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Length",String.valueOf(g.length));
System.out.println("壓縮後的資料的大小為:" + g.length);
response.getOutputStream().write(g);
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
doGet(request,response);
}
}
修改web.xml如下:
<servlet>
<servlet-name>encode</servlet-name>
<servlet-class>com.servlet.ResponseEncode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>encode</servlet-name>
<url-pattern>/encode</url-pattern>
</servlet-mapping>
2、運行結果
瀏覽器上顯示:123456789012345678901234…
好像沒有什麼效果。
3、測試壓縮方法
在瀏覽器上的訪問URL為:http://localhost:8080/webStudy/encode
所有的資料都很正常,但是好像什麼都沒有做,和普通的方法是一樣的。
利用apache commons的httpClient寫一個簡單的測試案例。(在Apache commons 系列部落格中有詳細介紹)
httpClient的測試原始碼:
package test.ffm83.commons.httpClient;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* httpClient 的簡單應用
* 基於4.x版本
* @author 範芳銘
*/
public class EasyHttpGetA {
public finalstatic void main(String[] args) throws Exception {
getHttpGetOld("http://www.baidu.com/");
getHttpGetOld("http://localhost:8080/webStudy/encode");
}
private staticvoid getHttpGetOld(String url) throws Exception{
HttpClient httpclient = newDefaultHttpClient(); //老方法,不推薦使用
try {
HttpGet httpget = newHttpGet(url);
System.out.println(StringUtils.center(url, 50,"="));
HttpResponse response =httpclient.execute(httpget); //老方法,不推薦使用
HttpEntity entity =response.getEntity();
System.out.println(response.getStatusLine());
String webContent = "";
if (entity != null) {
webContent= EntityUtils.toString(entity);
System.out.println("ResponsegetContentLength: " + entity.getContentLength());
System.out.println("ResponsetoString() length: " + webContent.length());
}
System.out.println(response.toString()); //顯示HTTP請求header
System.out.println("----------------------------------------");
httpget.abort();
}
finally {
httpclient.getConnectionManager().shutdown();
}
}
}
4、最終運行結果
我在這裡測試了兩個URL地址,一個是百度的,一個是http://localhost:8080/webStudy/encode
運行結果如下:
==============http://www.baidu.com/===============
HTTP/1.1 200 OK
Response getContentLength: -1
Response toString() length: 88174
HTTP/1.1 200 OK [Date: Mon, 02 Feb2015 07:35:35 GMT, Content-Type: text/html; charset=utf-8, Transfer-Encoding:chunked, Connection: Keep-Alive, Vary: Accept-Encoding, Set-Cookie:BAIDUID=79C3549FB148B3FD0457B06C79D0BB4C:FG=1; expires=Thu, 31-Dec-37 23:55:55GMT; max-age=2147483647; path=/; domain=.baidu.com, Set-Cookie:BAIDUPSID=79C3549FB148B3FD0457B06C79D0BB4C; expires=Thu, 31-Dec-37 23:55:55GMT; max-age=2147483647; path=/; domain=.baidu.com, Set-Cookie: BDSVRTM=0;path=/, Set-Cookie: BD_HOME=0; path=/, Set-Cookie: H_PS_PSSID=11384_6354_1426_11361_11156_10902_11226_11394_11101_11399_11277_11241_11280_11151_11243_11404_10618_10634;path=/; domain=.baidu.com, P3P: CP=" OTI DSP COR IVA OUR IND COM ",Cache-Control: private, Cxy_all: baidu+fefa91c7f05681df2e287f12aec4d30b, Expires:Mon, 02 Feb 2015 07:35:27 GMT, X-Powered-By: HPHP, Server: BWS/1.1, BDPAGETYPE:1, BDQID: 0xec3eeae200002e8a, BDUSERID: 0][email protected]
----------------------------------------
======http://localhost:8080/webStudy/encode=======
HTTP/1.1 200 OK
Response getContentLength: 35
Response toString() length: 35
HTTP/1.1 200 OK [Server:Apache-Coyote/1.1, Content-Encoding: gzip, Content-Length: 35, Date: Mon, 02Feb 2015 07:37:50 GMT] [email protected]
----------------------------------------
從工具中能夠看到:
Response getContentLength: 35
Response toString() length: 35
而從控制台列印出來的內容:
未經處理資料的大小為:300
壓縮後的資料的大小為:35
瀏覽器具備了自我解壓的能力,資料在傳輸過程中被壓縮,降低了頻寬的使用。
好記性不如爛筆頭16-http協議(2)和頁面資料壓縮傳遞