码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient官文总结-Guide

时间:2016-11-08 00:38:58      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:ann   one   div   实现   https   create   ensure   client   stream   

  打开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

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

HttpClient官文总结-Guide

标签:ann   one   div   实现   https   create   ensure   client   stream   

原文地址:http://www.cnblogs.com/bruceChan0018/p/6038409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!