Java

HTTP请求数据压缩

2018-05-28  本文已影响16人  爱码士平头哥

客户端:

GetMethod method = new GetMethod(url);//生成一个get方法实例  
  
method.setQueryString(queryString);//设置查询字符串  
method.addRequestHeader("Accept-Encoding", "gzip");//设置接受响应消息为gzip  
  
HttpClient client = new HttpClient();//生成执行get方法的客户端实例  
client.executeMethod(method);//执行get方法  
  
InputStream in = method.getResponseBodyAsStream();//获取响应消息体  
Header contentEncoding = method.getResponseHeader("Content-Encoding");//获取消息头Content-Encoding判断数据流是否gzip压缩过  
  
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {  
    GZIPInputStream gzipIn = new GZIPInputStream(in);  
    int len = Integer.parseInt(method.getResponseHeader("Content-Length").getValue());  
    byte[] b = new byte[len];  
    gzipIn.read(b);  
      
    String json = new String(b);  
    System.out.println(json);  
}  

服务端:

byte[] result = data.getBytes("UTF-8");  
  
if(response.getHeader("Accept-Encoding").equalsIgnoreCase("gzip"))  
{  
    // System.out.println("Before compression, the data size is :"+ result.length);  
    // Using gzip compress the data  
    ByteArrayOutputStream out = new ByteArrayOutputStream();  
    GZIPOutputStream gout = new GZIPOutputStream(out);  
    gout.write(json.getBytes("UTF-8"));  
    gout.close();  
    result = out.toByteArray();  
  
    // System.out.println("After compression, the data size is "+gzipResult.length);  
    this.getResp().setHeader("Content-Encoding","gzip");  
    this.getResp().setHeader("Content-Length", result.length+"");  
}  
  
response.getOutputStream().write(result);  
上一篇下一篇

猜你喜欢

热点阅读