Apache HttpCompenent 学习 (一) HttpCore

本文介绍了Apache HttpCore,它包含了实现HTTP协议的基础组件,如HttpMessage用于构建请求和响应,HttpEntity抽象了消息内容。HttpProtocolProcessor处理请求,由多个拦截器组成,其中拦截器对HTTP头进行验证。HTTP执行上下文用于组件间共享信息,但并发使用时需要注意线程安全性。

HttpCore 简介

顾名思义 httpcore包含了实现http协议最基本的一些组件,但同时足以通过最小的内存占用实现 client-side and server-side HTTP services
官方介绍

主要组件

HttpMessage (负责构建消息的)

1、HttpRequest&HttpResponse

介绍

两个接口都继承自HttpMessage

http消息 由Message header 和 messagebody 构成
http message 的介绍

status-line:
request:GET / HTTP/1.1
Response:HTTP/1.1 200 OK

使用

基本实现:

public  BasicHttpResponse(final StatusLine ,final ReasonPhraseCatalog catalog,  final Locale locale) {
         super();
         this.statusline = Args.notNull(statusline, "Status line");
         this.ver = statusline.getProtocolVersion();
         this.code = statusline.getStatusCode();
         this.reasonPhrase = statusline.getReasonPhrase();
         this.reasonCatalog = catalog;
         this.locale = locale;
     }

[Interface] HttpMessage 的一些公共方法(对消息头的处理)

[Public Method] addHeader(Header) : void
[Public Method] addHeader(String, String) : void
[Public Method] containsHeader(String) : boolean
[Public Method] getAllHeaders() : Header[]
[Public Method] getFirstHeader(String) : Header
[Public Method] getHeaders(String) : Header[]
[Public Method] getLastHeader(String) : Header
[Public Method] getParams() : HttpParams
[Public Method] getProtocolVersion() : ProtocolVersion
[Public Method] headerIterator() : HeaderIterator
[Public Method] removeHeader(Header) : void
[Public Method] removeHeaders(String) : void
[Public Method] setHeader(Header) : void
[Public Method] setHeader(String, String) : void
[Public Method] setHeaders(Header[]) : void

2、HttpEntity

介绍

抽象了http消息包含的内容,方便我们读取
Since an entity can represent both binary and character content, it has support for character encodings(支持编码)
比如

[RequestHeader]
Status Code:200 OK
Response Headers
alternate-protocol:443:quic,p=0.5
cache-control:private, max-age=0
content-encoding:gzip
content-type:text/html; charset=UTF-8
date:Tue, 31 Mar 2015 07:36:13 GMT

分类

  • 流式 streamed:通过字节流接收的或动态生成的内容,通常不可复用
  • 自包含?self-contained: The content is in memory or obtained by means that are independent from a connection or other entity. 可复用
  • 交换的 wrapping:从其他实体得到的
使用

读取相应的内容信息

System.out.println(response.getEntity().getContentEncoding());
System.out.println(response.getEntity().getContentLength());

读内容到io流

HttpResponse response;
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();
    try {
        // do something useful
    } finally {
        instream.close();
    }
}

Http Protocol Processor(负责处理请求的)

processor 协议处理程序

介绍

HTTP protocol processor 是一个实现了责任链模式的Protocol interceptor拦截器的集合
拦截器通常对顺序没有要求,如果拦截器之间有关联,就应该按照要求的顺序添加

  • 构造函数的签名:
public  [More ...] ImmutableHttpProcessor(
final List<HttpRequestInterceptor> requestInterceptors,
             final List<HttpResponseInterceptor> responseInterceptors) {
  • 执行http请求
 @Override


    public void  [More ...] process(
            final HttpRequest request,
            final HttpContext context) throws IOException, HttpException {


        for (final HttpRequestInterceptor requestInterceptor : this.requestInterceptors) {

            requestInterceptor.process(request, context);
        }

    }

    @Override
    public void  [More ...] process(

            final HttpResponse response,

            final HttpContext context) throws IOException, HttpException {

        for (final HttpResponseInterceptor responseInterceptor : this.responseInterceptors) {

            responseInterceptor.process(response, context);

        }
    }

}
使用
//初始化
HttpProcessor httpProcessor = HttpProcessorBuilder.create()
                .add(new RequestContent())
                .add(new RequestTargetHost())
                .add(new RequestConnControl())
                .add(new RequestUserAgent("Test/1.1"))
                .add(new RequestExpectContinue(true)).build();

protocol interceptors 拦截器

介绍

协议拦截器必须实现为线程安全的。类似于servlet、协议拦截器不应该使用实例变量,除非获得这些变量的方式是同步的。
主要是对http Header 做相应的验证
- 几种拦截器
- RequestContent 拦截发出的请求 设置content-length
- ResponseContent 拦截接收的响应
- RequestTargetHost 看名字就知道
- ResponseServer。。。

使用
//RequestConnControl(保证连接)的实现源码
public class RequestConnControl implements HttpRequestInterceptor {
    public RequestConnControl() {
    }

    public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
        Args.notNull(request, "HTTP request");
        String method = request.getRequestLine().getMethod();
        if(!method.equalsIgnoreCase("CONNECT")) {
            if(!request.containsHeader("Connection")) {
                request.addHeader("Connection", "Keep-Alive");
            }
        }
    }
}

HTTP execution context 上下文

介绍

为组件共享信息设计

HTTP context can be used to store a processing state for one message or several consecutive messages. Multiple logically related messages can participate in a logical session if the same context is reused between consecutive messages.

并发访问时 也要注意属性是不是线程安全的

/ IMPORTANT: Please note HTTP context implementation, even when thread safe, may not be used concurrently by multiple threads, as the context may contain thread unsafe attributes.

通常内容如下:
一次请求中httpcontext的内容

使用
//context保存了sessionid 标志同一会话
HttpProcessor httpproc = HttpProcessorBuilder.create()
        .add(new HttpRequestInterceptor() {
            public void process(
                    HttpRequest request,
                    HttpContext context) throws HttpException, IOException {
                String id = (String) context.getAttribute("session-id");
                if (id != null) {
                    request.addHeader("Session-ID", id);
                }
            }
        })
        .build();

HttpCoreContext context = HttpCoreContext.create();
HttpRequest request = new BasicHttpRequest("GET", "/");
httpproc.process(request, context);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值