关于Httpclient的总结(二)

(8)针对在HTTPClient采用压缩格式的文件的传输,必须采用拦截器进行特殊的处理
public class ClientGZipContentCompression {

    public final static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        //设置相关的压缩文件标识,在请求头的信息中
        httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
           
            public void process(
                    final HttpRequest request, 
                    final HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }

        });
        //设置相应相应的拦截器,用于处理接收到的拦截的压缩信息
        httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
           
            public void process(
                    final HttpResponse response, 
                    final HttpContext context) throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(
                                    new GzipDecompressingEntity(response.getEntity())); 
                            return;
                        }
                    }
                }
            }
            
        });
        
        HttpGet httpget = new HttpGet("http://www.apache.org/"); 
        
        // Execute HTTP request
        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println(response.getLastHeader("Content-Encoding"));
        System.out.println(response.getLastHeader("Content-Length"));
        System.out.println("----------------------------------------");

        HttpEntity entity = response.getEntity();
        
        if (entity != null) {
            String content = EntityUtils.toString(entity);
            System.out.println(content);
            System.out.println("----------------------------------------");
            System.out.println("Uncompressed size: "+content.length());
        }
        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();        
    }
   //压缩文件处理的实体包装类
    static class GzipDecompressingEntity extends HttpEntityWrapper {
        public GzipDecompressingEntity(final HttpEntity entity) {
            super(entity);
        }
        @Override
        public InputStream getContent()
            throws IOException, IllegalStateException {
            // the wrapped entity's getContent() decides about repeatability
            InputStream wrappedin = wrappedEntity.getContent();
            return new GZIPInputStream(wrappedin);
        }
        @Override
        public long getContentLength() {
            // length of ungzipped content is not known
            return -1;
        }

    } 
    
}
(9)在代理中添加相关访问权限
        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope("localhost", 8080), 
                new UsernamePasswordCredentials("username", "password"));

        HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https"); 
        HttpHost proxy = new HttpHost("localhost", 8080); 

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpGet httpget = new HttpGet("/");
        
        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);
        
        HttpResponse response = httpclient.execute(targetHost, httpget);
(10)针对特定的相应中信息比较多那么可以采用相关的相应处理器处理
     ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        实现类如下:
        public class BasicResponseHandler implements ResponseHandler<String>

关于HttpClient采用代理服务器的使用
        // 创建两个host对象,其中一个目标机器,和代理主机make sure to use a proxy that supports CONNECT
        HttpHost target = new HttpHost("issues.apache.org", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        //设置相关的注册信息 general setup
        SchemeRegistry supportedSchemes = new SchemeRegistry();

        // Register the "http" and "https" protocol schemes, they are
        // required by the default operator to look up socket factories.
        supportedSchemes.register(new Scheme("http", 
                PlainSocketFactory.getSocketFactory(), 80));
        supportedSchemes.register(new Scheme("https", 
                SSLSocketFactory.getSocketFactory(), 443));

        //设置相关的参数的信息
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);
        //客户端连接管理器
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, 
                supportedSchemes);

        DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);
        //设置请求采用代理的
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
 
        HttpGet req = new HttpGet("/");
        //执行请求并处理
        System.out.println("executing request to " + target + " via " + proxy);
        HttpResponse rsp = httpclient.execute(target, req);
        HttpEntity entity = rsp.getEntity();
(11)针对多线程的Httpclient中采用的特殊的连接管理
        // Create and initialize HTTP parameters
        HttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 100);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        
        // Create and initialize scheme registry 
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(
                new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        
        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        HttpClient httpClient = new DefaultHttpClient(cm, params);

相关推荐