码迷,mamicode.com
首页 > 其他好文 > 详细

客户端HttpClient处理 Servlet Gzip

时间:2014-05-07 19:14:17      阅读:359      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   ext   

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

一: 服务端

bubuko.com,布布扣
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);
    }
}
bubuko.com,布布扣

二:客户端

  采用HttpClient3.1。

(1)UngzipPostMethod.java

bubuko.com,布布扣
/**
 * 继承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;
        }
    }
}
bubuko.com,布布扣

(2)HttpUtil.java

bubuko.com,布布扣
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();
    }
}
bubuko.com,布布扣

(3)Test.java

bubuko.com,布布扣
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));
    }
}
bubuko.com,布布扣

 

 

客户端HttpClient处理 Servlet Gzip,布布扣,bubuko.com

客户端HttpClient处理 Servlet Gzip

标签:style   blog   class   code   java   ext   

原文地址:http://www.cnblogs.com/yshyee/p/3709847.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!