`
Jatula
  • 浏览: 279258 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

HttpClient Examples:Custom protocol interceptors

阅读更多

官方主頁:http://hc.apache.org/

 

Components

Custom protocol interceptors

This example shows the use of protocol interceptors to transparently modify properties of HTTP messages sent / received by the HTTP client.

In this particular case HTTP client is made capable of transparent content GZIP compression by adding two protocol interceptors: a request interceptor that adds 'Accept-Encoding: gzip' header to all outgoing requests and a response interceptor that automatically expands compressed response entities by wrapping them with a uncompressing decorator class. The use of protocol interceptors makes content compression completely transparent to the consumer of the HttpClient interface.

 

自定义拦截协议

 

这个例子表明使用协议拦截透过修改属性的HTTP邮件发送/接收的HTTP客户端。

 

在这种特定情况下的HTTP客户端是能够透过内容gzip压缩增加了两个议定书拦截:请求拦截,增加了'接受编码: gzip或'标头所有即将离任的要求和反应,它可以自动拦截扩展压缩响应这些实体的包装与uncompressing装饰类。使用协议拦截使得完全透明的内容压缩到消费者的HttpClient接口。

 

package cn.lake.util;

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

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * Demonstration of the use of protocol interceptors to transparently 
 * modify properties of HTTP messages sent / received by the HTTP client.
 * <p/>
 * In this particular case HTTP client is made capable of transparent content 
 * GZIP compression by adding two protocol interceptors: a request interceptor
 * that adds 'Accept-Encoding: gzip' header to all outgoing requests and
 * a response interceptor that automatically expands compressed response
 * entities by wrapping them with a uncompressing decorator class. The use of
 * protocol interceptors makes content compression completely transparent to 
 * the consumer of the {@link org.apache.http.client.HttpClient HttpClient}
 * interface.
 */
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());
		}
	}

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

	}

}

 

翻譯的不好,請見諒!

 

分享到:
评论

相关推荐

    HttpClient问题:The server failed to respond with a valid HTTP resp

    RequestConfig config = RequestConfig.custom() .setConnectTimeout(10000) // 连接超时,单位毫秒 .setSocketTimeout(10000) // 读取超时,单位毫秒 .build(); HttpGet get = new HttpGet(url); get.set...

    可用org.apache.commons.httpclient-3.1.0.jar.zip

    import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory; import org.apache.commons.httpclient.util.HttpURLConnection;

    commons-httpclient-3.1jar包

    《Apache Commons HttpClient 3.1详解》 Apache Commons HttpClient 是一个功能强大的Java库,专为实现客户端HTTP通信而设计。这个3.1版本是HttpClient的一个重要里程碑,它提供了丰富的功能和改进,使得开发者能够...

    httpclient-4.5.12-API文档-中文版.zip

    Maven坐标:org.apache.httpcomponents:httpclient:4.5.12; 标签:apache、httpcomponents、httpclient、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档...

    httpclient-4.5.13-API文档-中文版.zip

    Maven坐标:org.apache.httpcomponents:httpclient:4.5.13; 标签:apache、httpcomponents、httpclient、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档...

    commons-httpclient-3.0.jar JAVA中使用HttpClient可以用到

    《JAVA中使用HttpClient:commons-httpclient-3.0.jar详解》 在JAVA开发中,进行HTTP请求时,Apache的HttpClient库是一个不可或缺的工具。本文将深入解析`commons-httpclient-3.0.jar`,它是HttpClient的一个重要...

    HttpClient依赖jar包.zip

    本资源"HttpClient依赖jar包.zip"包含了实现这些功能所需的jar文件,使得开发者能够方便地在Java项目中集成HttpClient库。 HttpClient库的核心功能包括: 1. **发起HTTP/HTTPS请求**:HttpClient允许开发者发送...

    httpclient-4.5jar包

    《HttpClient 4.5详解与应用实践》 HttpClient是一个开源的Java库,由Apache软件基金会维护,主要用于在HTTP协议上实现客户端的通信。版本4.5是HttpClient的一个稳定版本,提供了许多增强的功能和优化,使其成为...

    httpclient-4.5.13-API文档-中英对照版.zip

    Maven坐标:org.apache.httpcomponents:httpclient:4.5.13; 标签:apache、httpcomponents、httpclient、jar包、java、中英对照文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览...

    commons-httpclient3.1.jar,commons-codec1.3.jar,commons-logging1.1.1.jar

    标题中的"commons-httpclient3.1.jar,commons-codec1.3.jar,commons-logging1.1.1.jar"指的是三个关键的Java库文件,它们是Apache HttpClient项目的一部分,用于在Java应用程序中实现HTTP通信。这些JAR(Java ...

    org.apache.commons.httpclient-3.1.jar

    《Apache Commons HttpClient 3.1:HTTP客户端编程的基石》 ...然而,需要注意的是,HttpClient 3.1已不再维护,最新的稳定版本为HttpClient 4.x,对于新项目建议使用更现代的版本以获取更好的性能和兼容性。

    httpclient-4.5jar

    httpclient-4.5所需jar包,里面包含httpclient-4.5.jar等等10个必须的开发包。 1.commons-codec-1.9.jar 2.commons-logging-1.2.jar 3.fluent-hc-4.5.jar 4.httpclient-4.5.jar 5.httpclient-cache-4.5.jar 6....

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setSSLSocketFactory(sslSocketFactory) .build(); ``` 3. 执行请求: 现在你可以像之前一样使用这个...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    HttpClientUtil:一个Http请求使用HttpClient访问服务器,我们也可以上传文件到服务器,比如文件或图片。它提供接口来更新你的上传进度

    - 创建 HttpClient 实例:首先,我们需要创建一个 HttpClient 实例,这可以通过 HttpClientBuilder 或直接使用 HttpClients.createDefault() 方法完成。 - 创建请求:然后,我们需要构造一个 HttpRequestBase 对象...

    ribbon-httpclient-2.2.5.jar

    ribbon-httpclient-2.2.5.jar

    httpClient组合包.zip

    此外,HttpClient还支持异步操作,可以在多线程环境中高效地处理并发请求。 2. **httpcore-4.4.12.jar**:这是HttpClient的核心库,包含了HTTP协议的基本组件,如连接管理、请求和响应模型、编码器和解码器等。...

    httpclient-4.5.jar

    在这个版本中,我们关注的是`httpclient-4.5.jar`,这是一个包含了HttpClient 4.5核心功能的Java库。这个库的发布日期为2016年7月19日,它提供了许多改进和新特性,旨在帮助开发者更高效、更稳定地构建网络应用程序...

    wechatpay-apache-httpclient:微信支付 APIv3 Apache HttpClient装饰器(decorator)

    wechatpay-apache-httpclient 概览 的扩展,实现了请求签名的生成和应答签名的验证。...implementation 'com.github.wechatpay-apiv3:wechatpay-apache-httpclient:0.2.2' Maven 加入以下依赖 &lt;groupId&gt;com.github.w

    最全最新httpclient4.3.3

    1. HttpClient:主接口,用于创建和执行HTTP请求。 2. HttpCore:基础的HTTP协议处理组件,负责连接管理和传输。 3. HttpClientContext:上下文对象,存储了请求和响应过程中的状态信息。 4. HttpRequestExecutor:...

Global site tag (gtag.js) - Google Analytics