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;
        }
    }

}
 

你可能感兴趣的:(java,apache,jsp)