HttpCLient实现对被GZip压缩过的Response进行解压

发送请求(要求服务端对response进行GZip压缩):

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;

public class TestGzip {

	private final static String url = "http://localhost:8888/ltest.jsp";

	public static void main(String[] args) throws Exception{
		HttpClient http = new HttpClient();
		CustomGetMethod get = new CustomGetMethod(url);
		
       //添加头信息告诉服务端可以对Response进行GZip压缩
    	get.setRequestHeader("Accept-Encoding", "gzip, deflate");
        try {
            int statusCode = http.executeMethod(get);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + get.getStatusLine());
            }

            //打印解压后的返回信息
            System.out.println(get.getResponseBodyAsString());
        } catch (Exception e) {
            System.err.println("页面无法访问");
            e.printStackTrace();
        } finally {
		get.releaseConnection();
        }
	}
}
 

下面是CustomGetMethod.java的内容,getResponseBodyAsString()方法被重写,加入了解压功能

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;



public class CustomGetMethod extends org.apache.commons.httpclient.methods.GetMethod{
	
	public CustomGetMethod(String uri) {
		super(uri);
	}

	
	/**
	 * Get response as string whether response is GZipped or not
	 * 
	 * @return
	 * @throws IOException
	 */
	@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) {
    				//For GZip response
    				InputStream is = getResponseBodyAsStream();
    	            gzin = new GZIPInputStream(is);
    	            
    	            InputStreamReader isr = new InputStreamReader(gzin, getResponseCharSet()); 
    	            java.io.BufferedReader br = new java.io.BufferedReader(isr);
    	            StringBuffer sb = new StringBuffer();
    	            String tempbf;
    	            while ((tempbf = br.readLine()) != null) {
    	                sb.append(tempbf);
    	                sb.append("\r\n");
    	            }
    	            isr.close();
    	            gzin.close();
    	            return sb.toString();
    			}  else {
				//For deflate response
				return super.getResponseBodyAsString();
			}
        } else {
            return null;
        }
    }

}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值