Android中使用gzip传递数据

HTTP协议上的GZIP编码是一种用来改进WEB应用程序性能的技术。大流量的WEB站点常常使用GZIP压缩技术来减少文件大小,减少文件大小有两个明显的好处,一是可以减少存储空间,二是通过网络传输文件时,可以减少传输的时间。作者在写这篇博客时经过测试,4.4MB的文本数据经过Gzip传输到客户端之后变为392KB,压缩效率极高。

一.服务端

服务端有2种方式去压缩,一种可以自己压缩,但是更推荐第二种方式,用PrintWriter作为输出流,工具类代码如下

  1. /** 
  2.          * 判断浏览器是否支持 gzip 压缩 
  3.          * @param req 
  4.          * @return boolean 值 
  5.          */  
  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.       
/**
		 * 判断浏览器是否支持 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;
			}
		}

		/**
		 * 创建 以 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 中设置返回类型为 gzip
				resp.setHeader("content-encoding", "gzip");
			} else { // // 客户端 不支持 gzip
				pw = resp.getWriter();
			}
			return pw;
		}
	

servlet代码如下:
  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. }  
	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);
	}
在代理软件中跟踪到的数据如下:
  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¤†ˆ  
‹«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@
¢òós3óÒ2“‘Uœþºýè–Ïg÷€Tå—$–¤› +r·¸ðä‡Zh¤†ˆ

实际数据如下:

  1. {"ContentLayer":{"title":"内容层"},"PageLink":{"title":"页面跳转"},"WebBrowser":{"title":"浏览器"},"InlinePage":{"title":"内嵌页面"},"VideoComp":{"title":"视频"},"PopButton":{"title":"内容开关"},"ZoomingPic":{"title":"缩放大图"},"Rotate360":{"title":"360度旋转"}}  
{"ContentLayer":{"title":"内容层"},"PageLink":{"title":"页面跳转"},"WebBrowser":{"title":"浏览器"},"InlinePage":{"title":"内嵌页面"},"VideoComp":{"title":"视频"},"PopButton":{"title":"内容开关"},"ZoomingPic":{"title":"缩放大图"},"Rotate360":{"title":"360度旋转"}}

二.Android客户端

得到HttpClient代码:

  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.     }  
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:

  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.     }  
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;
	}

访问网络代码:

  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.     }  
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;
			 */

		}

	}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值