HttpClient官文总结-Guide

本文介绍了Apache HttpClient 4.5模块的使用方法,包括GET/POST请求示例及响应处理、连接释放、配置定制等内容,并提供了多种实用场景的示例,如通过代理发送请求、使用自定义SSL上下文等。

  打开Commons HttpClient-3.x的官网会发现,这个项目已经停止更新,取代它的是Apache HttpComponents项目的HttpClient和HttpCore模块,所以重点就关注新的工程。

  在HttpClient模块中,官方目前用到的最新版本是HC4.5。

  首先给出了简单的例子GET/POST,但这个例子并不能直接放到实际场景中使用,具体查看注释说明:

package org.apache.http.examples.client;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class QuickStart {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet("http://httpbin.org/get");
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            // 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.
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }
HttpPost httpPost
= new HttpPost("http://httpbin.org/post"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new BasicNameValuePair("password", "secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); } } finally { httpclient.close(); } } }

注释主要是说,用完要关ClosableHttpResponse,响应在消费完之前不能被重用,否则会被连接管理所丢弃。

  接下来官文中给出了一些更复杂的实例,先来个链接:http://hc.apache.org/httpcomponents-client-4.5.x/examples.html。在给出的HttpClient Example中,涉及到了可能会在实际场景中出现的各种场景,以及一些推荐的做法:

Response handling
    This example demonstrates how to process HTTP responses using a response handler. This is the recommended way of executing HTTP requests and processing HTTP responses. This approach enables the caller to concentrate on the process of digesting HTTP responses and to delegate the task of system resource deallocation to HttpClient. The use of an HTTP response handler guarantees that the underlying HTTP connection will be released back to the connection manager automatically in all cases.
Manual connection release
    This example demonstrates how to ensure the release of the underlying HTTP connection back to the connection manager in case of a manual processing of HTTP responses.
HttpClient configuration
    This example demonstrates how to customize and configure the most common aspects of HTTP request execution and connection management.
Abort method
    This example demonstrates how to abort an HTTP request before its normal completion.
Client authentication
    This example uses HttpClient to execute an HTTP request against a target site that requires user authentication.
Request via a proxy
    This example demonstrates how to send an HTTP request via a proxy.
Proxy authentication
    A simple example showing execution of an HTTP request over a secure connection tunneled through an authenticating proxy.
Chunk encoded POST
    This example shows how to stream out a request entity using chunk encoding.
Custom execution context
    This example demonstrates the use of a local HTTP context populated custom attributes.
Form based logon
    This example demonstrates how HttpClient can be used to perform form-based logon.
Threaded request execution
    An example that executes HTTP requests from multiple worker threads.
Custom SSL context
    This example demonstrates how to create secure connections with a custom SSL context.
Preemptive BASIC authentication
    This example shows how HttpClient can be customized to authenticate preemptively using BASIC scheme. Generally, preemptive authentication can be considered less secure than a response to an authentication challenge and therefore discouraged.
Preemptive DIGEST authentication
    This example shows how HttpClient can be customized to authenticate preemptively using DIGEST scheme. Generally, preemptive authentication can be considered less secure than a response to an authentication challenge and therefore discouraged.
Proxy tunnel
    This example shows how to use ProxyClient in order to establish a tunnel through an HTTP proxy for an arbitrary protocol.
Multipart encoded request entity
    This example shows how to execute requests enclosing a multipart encoded entity.
Native Windows Negotiate/NTLM
    This example shows how to make use of Native Windows Negotiate/NTLM authentication when running on Windows OS.

  这些实例包含了response handling接口自动释放链接、手动释放链接、HttpClient参数配置、中途停止请求以及各种权限、代理、多线程请求、Https等,其实没有什么Util可以完全囊括所有的业务场景,只能是根据实际的场景去适配更为合适的Util,所以还是需要深入地了解学习基础协议以及原理,才能写出更好的Util。

  相对而言,另一个模块HttpCore就是更为底层的实现。官方的解释:

HttpCore is a set of low level HTTP transport components that can be used to build custom client and server side HTTP services with a minimal footprint. HttpCore supports two I/O models: blocking I/O model based on the classic Java I/O and non-blocking, event driven I/O model based on Java NIO.

所以在常用的场景中,该模块用到的几率会比较小,但如果想了解细节,这部分绝对不可错过,而且文档也说明了该模块支持两种IO模型,Java IO以及Java NIO,所以网络IO这一块儿也是需要把基础内容掌握好。

  另外给出这两个模块的官方guide pdf:

http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/pdf/httpclient-tutorial.pdf
http://hc.apache.org/httpcomponents-core-4.4.x/tutorial/pdf/httpcore-tutorial.pdf

  仔细研读,定会收获多多。

转载于:https://www.cnblogs.com/bruceChan0018/p/6038409.html

httpclient4 中版帮助档,最新方版翻译版 前言 超本传输协议(HTTP)也许是当今互联网上使用的最重要的协议了。Web服务,有网络功能的设备和网络计算的发展,都持续扩展了HTTP协议的角色,超越了用户使用的Web浏览器范畴,同时,也增加了需要HTTP协议支持的应用程序的数量。 尽管java.net包提供了基本通过HTTP访问资源的功能,但它没有提供全面的灵活性和其它很多应用程序需要的功能。HttpClient就是寻求弥补这项空白的组件,通过提供一个有效的,保持更新的,功能丰富的软件包来实现客户端最新的HTTP标准和建议。 为扩展而设计,同时为基本的HTTP协议提供强大的支持,HttpClient组件也许就是构建HTTP客户端应用程序,比如web浏览器,web服务端,利用或扩展HTTP协议进行分布式通信的系统的开发人员的关注点。 1. HttpClient的范围 基于HttpCore[http://hc.apache.org/httpcomponents-core/index.html]的客户端HTTP运输实现库 基于经典(阻塞)I/O 内容无关 2. 什么是HttpClient不能做的 HttpClient 不是一个浏览器。它是一个客户端的HTTP通信实现库。HttpClient的目标是发送和接收HTTP报HttpClient不会去缓存内容,执行 嵌入在HTML页面中的javascript代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和HTTP运输无关的功能。 第一章 基础 1.1 执行请求 ......
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值