Apache HttpComponents 5

HttpComponents 概述

超文本传输协议(HTTP)可能是当今互联网上使用的最重要的协议。Web 服务、支持网络的设备和网络计算的增长继续将 HTTP 协议的作用扩展到用户驱动的 Web 浏览器之外,同时增加了需要 HTTP 支持的应用程序数量。

HttpComponents 专为扩展而设计,同时为基本 HTTP 协议提供强大的支持,任何构建 HTTP 感知客户端和服务器应用程序(如 Web 浏览器、Web 爬虫、HTTP 代理、Web 服务传输库或利用或扩展 HTTP 协议进行分布式通信的系统)的人都可能对 HttpComponents 感兴趣。

HttpComponents Core

HttpCore 是一组低级 HTTP 传输组件,可用于以最小的占用空间构建自定义客户端和服务器端 HTTP 服务。HttpCore 支持两种 I/O 模型:基于经典 Java I/O 的阻塞 I/O 模型和基于 Java NIO 的非阻塞、事件驱动的 I/O 模型。

HttpComponents Client

HttpClient 是基于 HttpCore 的符合 HTTP/1.1 的 HTTP 代理实现。它还为客户端身份验证、HTTP 状态管理和 HTTP 连接管理提供了可重用的组件。HttpComponents Client 是 Commons HttpClient 3.x 的继承者和替代品。强烈建议共享资源HttpClient的用户进行升级。

文档

快速开始

  • 下载最新 HttpClient 5.2 版本的“二进制”包,或使用您选择的依赖项管理器配置依赖项 HttpClient 和 Fluent HC 模块,如此处所述。
  • HttpClient 5.2 需要 Java 1.8 或更高版本。
  • 下面的代码片段说明了如何使用 HttpClient 本机 API 执行 HTTP GET 和 POST 请求。
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
    ClassicHttpRequest httpGet = ClassicRequestBuilder.get("http://httpbin.org/get")
            .build();
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    httpclient.execute(httpGet, response -> {
        System.out.println(response.getCode() + " " + response.getReasonPhrase());
        final HttpEntity entity1 = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
        return null;
    });

    ClassicHttpRequest httpPost = ClassicRequestBuilder.post("http://httpbin.org/post")
            .setEntity(new UrlEncodedFormEntity(Arrays.asList(
                    new BasicNameValuePair("username", "vip"),
                    new BasicNameValuePair("password", "secret"))))
            .build();
    httpclient.execute(httpPost, response -> {
        System.out.println(response.getCode() + " " + response.getReasonPhrase());
        final HttpEntity entity2 = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return null;
    });
}
  • 可以使用更简单(尽管不太灵活)fluent API 执行相同的请求。
// The fluent API relieves the user from having to deal with manual deallocation of system
// resources at the cost of having to buffer response content in memory in some cases.

Request.Get("http://targethost/homepage")
    .execute().returnContent();
Request.Post("http://targethost/login")
    .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())
    .execute().returnContent();
  • 下面的代码片段演示了如何使用 HttpClient 异步 API 执行 HTTP 请求。
try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
    // Start the client
    httpclient.start();

    // Execute request
    SimpleHttpRequest request1 = SimpleRequestBuilder.get("http://httpbin.org/get").build();
    Future<SimpleHttpResponse> future = httpclient.execute(request1, null);
    // and wait until response is received
    SimpleHttpResponse response1 = future.get();
    System.out.println(request1.getRequestUri() + "->" + response1.getCode());

    // One most likely would want to use a callback for operation result
    CountDownLatch latch1 = new CountDownLatch(1);
    SimpleHttpRequest request2 = SimpleRequestBuilder.get("http://httpbin.org/get").build();
    httpclient.execute(request2, new FutureCallback<SimpleHttpResponse>() {

        @Override
        public void completed(SimpleHttpResponse response2) {
            latch1.countDown();
            System.out.println(request2.getRequestUri() + "->" + response2.getCode());
        }

        @Override
        public void failed(Exception ex) {
            latch1.countDown();
            System.out.println(request2.getRequestUri() + "->" + ex);
        }

        @Override
        public void cancelled() {
            latch1.countDown();
            System.out.println(request2.getRequestUri() + " cancelled");
        }

    });
    latch1.await();

    // In real world one most likely would want also want to stream
    // request and response body content
    CountDownLatch latch2 = new CountDownLatch(1);
    AsyncRequestProducer producer3 = AsyncRequestBuilder.get("http://httpbin.org/get").build();
    AbstractCharResponseConsumer<HttpResponse> consumer3 = new AbstractCharResponseConsumer<HttpResponse>() {

        HttpResponse response;

        @Override
        protected void start(HttpResponse response, ContentType contentType) throws HttpException, IOException {
            this.response = response;
        }

        @Override
        protected int capacityIncrement() {
            return Integer.MAX_VALUE;
        }

        @Override
        protected void data(CharBuffer data, boolean endOfStream) throws IOException {
            // Do something useful
        }

        @Override
        protected HttpResponse buildResult() throws IOException {
            return response;
        }

        @Override
        public void releaseResources() {
        }

    };
    httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {

        @Override
        public void completed(HttpResponse response3) {
            latch2.countDown();
            System.out.println(request2.getRequestUri() + "->" + response3.getCode());
        }

        @Override
        public void failed(Exception ex) {
            latch2.countDown();
            System.out.println(request2.getRequestUri() + "->" + ex);
        }

        @Override
        public void cancelled() {
            latch2.countDown();
            System.out.println(request2.getRequestUri() + " cancelled");
        }

    });
    latch2.await();

}

HttpClient示例

https://hc.apache.org/httpcomponents-client-5.2.x/examples.html

迁移升级指南

Migrate Guide

猜你喜欢

转载自blog.csdn.net/qq_26824159/article/details/131437822