首页 > 代码库 > 客户端HttpClient处理 Servlet Gzip

客户端HttpClient处理 Servlet Gzip

  服务端采用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));
    }
}