接下來,讓我解說一下如何在Android系統(tǒng)中使用gzip進(jìn)行數(shù)據(jù)傳遞
HTTP協(xié)議上的GZIP編碼是一種用來改進(jìn)WEB應(yīng)用程序性能的技術(shù)。大流量的WEB站點(diǎn)常常使用GZIP壓縮技術(shù)來減少文件大小,減少文件大小有兩個(gè)明顯的好處,一是可以減少存儲(chǔ)空間,二是通過網(wǎng)絡(luò)傳輸文件時(shí),可以減少傳輸?shù)臅r(shí)間。作者在寫這篇博客時(shí)經(jīng)過測試,4.4MB的文本數(shù)據(jù)經(jīng)過Gzip傳輸?shù)娇蛻舳酥笞優(yōu)?92KB,壓縮效率極高。
一.服務(wù)端
服務(wù)端有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)) { // 客戶端 不支持 gzip
return false;
} else { // 支持 gzip 壓縮
return true;
}
}
/**
* 創(chuàng)建 以 gzip 格式 輸出的 PrintWriter 對象,如果瀏覽器不支持 gzip 格式,則創(chuàng)建普通的 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 中設(shè)置返回類型為 gzip
resp.setHeader("content-encoding", "gzip");
} else { // // 客戶端 不支持 gzip
pw = 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/":/"內(nèi)容層/"},/"PageLink/":{/"title/":/"頁面跳轉(zhuǎn)/"},/"WebBrowser/":{/"title/":/"瀏覽器/"},"
+ "/"InlinePage/":{/"title/":/"內(nèi)嵌頁面/"},/"VideoComp/":{/"title/":/"視頻/"},"
+ "/"PopButton/":{/"title/":/"內(nèi)容開關(guān)/"},/"ZoomingPic/":{/"title/":/"縮放大圖/"},"
+ "/"Rotate360/":{/"title/":/"360度旋轉(zhuǎn)/"}}";
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);
}
在代理軟件中跟蹤到的數(shù)據(jù)如下:
‹«VrÎÏ+IÍ+ñI¬L-R²ªV*É,ÉIU²R:rëÄÝM•ju”ÓS}2ó²‘e/m>üìÌë«@òá©INEùåŨúŸ¬?pàØw¼g^Nf^*ÈTóo™R
主站蜘蛛池模板:
保山市|
和静县|
潞城市|
新化县|
桓台县|
五台县|
临澧县|
长岭县|
丰顺县|
甘泉县|
多伦县|
白城市|
台中县|
尉犁县|
来宾市|
九寨沟县|
合作市|
昌都县|
金堂县|
宁国市|
阜康市|
七台河市|
会宁县|
黔江区|
马龙县|
左云县|
泗水县|
济宁市|
瓮安县|
杂多县|
碌曲县|
嵩明县|
平和县|
凤阳县|
桑日县|
门源|
铁力市|
岳池县|
华宁县|
惠州市|
兴安县|