服务端采用gzip对文本内容进行压缩处理,客户端使用HttpClient获取数据并进行gzip解压缩。

一: 服务端

public class GzipTestServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/html;charset=UTF-8"); String str = "中文测试this is a test!"; if (isGzipSupport(request)) {//支持gzip
response.setHeader("Content-Encoding", "gzip");
OutputStream os = response.getOutputStream();
GZIPOutputStream gs = new GZIPOutputStream(os);
gs.write(str.getBytes("UTF-8"));//解决中文乱码问题
gs.finish();
gs.close();
os.close();
} else {
PrintWriter out = response.getWriter();
out.write(str);
out.flush();
out.close();
}
} /**
* 判断客户端是否要求进行gzip压缩处理
* @param request
* @return
*/
private boolean isGzipSupport(HttpServletRequest request) {
String headEncoding = request.getHeader("accept-encoding");
return (headEncoding != null && (headEncoding.indexOf("gzip") != -1));
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

二:客户端

  采用HttpClient3.1。

(1)UngzipPostMethod.java

/**
* 继承PostMethod重写getResponseBodyAsString方法支持Gzip解压缩*/
public class UngzipPostMethod extends org.apache.commons.httpclient.methods.PostMethod{
public UngzipPostMethod(String uri){
super(uri);
} @Override
public String getResponseBodyAsString() throws IOException {
GZIPInputStream gzin;
if(getResponseBody()!=null ||getResponseStream() != null ){
if(getResponseHeader("Content-Encoding") != null && getResponseHeader("Content-Encoding").getValue().toLowerCase().indexOf("gzip") != -1) {
InputStream is = getResponseBodyAsStream();
gzin = new GZIPInputStream(is); InputStreamReader isr = new InputStreamReader(gzin,getResponseCharSet()); BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String tmp;
while((tmp = br.readLine())!=null){
sb.append(tmp);
sb.append("\r\n");
}
br.close();
isr.close();
return sb.toString();
}else{
//否则正常返回
return super.getResponseBodyAsString();
}
}else{
return null;
}
}
}

(2)HttpUtil.java

public class HttpUtil {
/**
* 获取到解压缩的内容
* @param url
* @param list
* @return
*/
public String postGzipRequest(String url, List<NameValuePair> list){
HttpClient client = new HttpClient();
UngzipPostMethod post = new UngzipPostMethod(url);
post.setRequestHeader("Accept-Encoding", "gzip, deflate");
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
StringBuilder sb = new StringBuilder(); if(list!=null){
int len = list.size();
NameValuePair[] params = new NameValuePair[len];
for(int i=0; i<len; i++){
params[i] = list.get(i);
}
post.setRequestBody(params);
}
try {
//执行post
int statusCode = client.executeMethod(post); if (statusCode == HttpStatus.SC_OK) {
sb.append(post.getResponseBodyAsString());
} } catch (IOException ex) {
java.util.logging.Logger.getLogger(HttpUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return sb.toString();
}
}

(3)Test.java

public class Test {
public static void main(String args[]){
HttpUtil httpUtil = new HttpUtil();
String url = "http://localhost:8080/tsmanager/GzipTestServlet.do";
System.out.println("内容:"+httpUtil.postGzipRequest(url, null));
}
}

客户端HttpClient处理 Servlet Gzip的更多相关文章

  1. HttpClient学习整理

    HttpClient简介HttpClient 功能介绍    1. 读取网页(HTTP/HTTPS)内容    2.使用POST方式提交数据(httpClient3)    3. 处理页面重定向    ...

  2. android之HttpClient

    Apache包是对android联网访问封装的很好的一个包,也是android访问网络最常用的类. 下面分别讲一下怎么用HttpClient实现get,post请求. 1.Get 请求 HttpGet ...

  3. android HTTPclient

    Apache包是对android联网访问封装的很好的一个包,也是android访问网络最常用的类. 下面分别讲一下怎么用HttpClient实现get,post请求. 1.Get 请求 1 2 3 4 ...

  4. HttpClient与APS.NET Web API:请求内容的压缩与解压

    首先说明一下,这里的压缩与解压不是通常所说的http compression——那是响应内容在服务端压缩.在客户端解压,而这里是请求内容在客户端压缩.在服务端解压. 对于响应内容的压缩,一般Web服务 ...

  5. java apache commons HttpClient发送get和post请求的学习整理(转)

    文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...

  6. httpclient模拟浏览器get\post

    一般的情况下我们都是使用IE或者Navigator浏览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据等等.所访问的这些页面有的仅 仅是一些普通的页面,有的需要用户登录后方可使用,或者需 ...

  7. HTTP协议 Servlet入门 Servlet工作原理和生命周期 Servlet细节 ServletConfig对象

    1 HTTP协议特点   1)客户端->服务端(请求request)有三部份     a)请求行--请求行用于描述客户端的请求方式.请求的资源名称,以及使用的HTTP协议版本号 请求行中的GET ...

  8. Android中利用httpclient进行网络通信的方法(以用户登录为例说明)

    http://www.android100.org/html/201406/09/22915.html 1.服务器端 服务器端和android没有太大关系,对J2EE比较熟悉的话写起来应该很容易,这里 ...

  9. HttpClient使用详解

    http://itindex.net/detail/52566-httpclient HttpClient使用详解 标签: httpclient | 发表时间:2015-01-22 12:07 | 作 ...

随机推荐

  1. php----浅谈一下empty isset is_null的用处

    } }    {      }  {       } } }    {      }  {       } is_null():判断变量是否为null if ($a){} 那这个未声明变量会报noti ...

  2. 关于hash

    http://rapheal.iteye.com/blog/1142955 关于javascript hash

  3. poj3294 --Life Forms

    Life Forms Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 12483   Accepted: 3501 Descr ...

  4. VS2008资源问题解决方法

    错误提示:C:/Program Files/Microsoft SDKs/Windows/v6.0A// Include/PrSht.h(0) error RC2247 : SYMBOL name t ...

  5. paip.Adblock屏蔽onlinedown华军软件园的4秒下载广告总结..

    paip.Adblock屏蔽onlinedown华军软件园的4秒下载广告总结..      作者Attilax ,  EMAIL:1466519819@qq.com  来源:attilax的专栏 地址 ...

  6. haproxy 负载elasticsearch 切换

    Attempted to send a bulk request to Elasticsearch configured at '["http://192.168.32.152:9200&q ...

  7. SQL 如何表示引号

    SELECT ename || '''' || ' 的工作是 ' || ' ' || job || '''' AS msg FROM emp WHERE deptno = 10; ' '' ' 第一个 ...

  8. Hdu1384-Intervals(差分约束)

    Problem Description You are given n closed, integer intervals [ai, bi] and n integers c1, ..., cn.Wr ...

  9. UVa10340.All in All

    题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem& ...

  10. 《Algorithms 4th Edition》读书笔记——2.4 优先队列(priority queue)-Ⅴ

    命题Q.对于一个含有N个元素的基于堆叠优先队列,插入元素操作只需要不超过(lgN + 1)次比较,删除最大元素的操作需要不超过2lgN次比较. 证明.由命题P可知,两种操作都需要在根节点和堆底之间移动 ...