第二章。Connection management链接管理
2.1. 2.1。Connection persistence链接持久性
The process of establishing a connection from one host to another is quite complex and involves multiple packet exchanges between two endpoints, which can be quite time consuming. 创建链接的过程从一个主机,另外一个是至关复杂的,涉及到多个包两个端点之间的交流,这是很是耗时的。The overhead of connection handshaking can be significant, especially for small HTTP messages. 链接的开销握手会很大,尤为是对小HTTP消息。One can achieve a much higher data throughput if open connections can be re-used to execute multiple requests.人能达到一个更高的数据吞吐量若是打开的链接能够被重用来执行多个请求。java
HTTP/1.1 states that HTTP connections can be re-used for multiple requests per default. HTTP / 1.1指出HTTP链接能够重复用于多个请求/违约。HTTP/1.0 compliant endpoints can also use a mechanism to explicitly communicate their preference to keep connection alive and use it for multiple requests. HTTP / 1.0兼容端点也可使用一种机制来明确地传达他们的偏好来保持链接活着,用它来多个请求。HTTP agents can also keep idle connections alive for a certain period time in case a connection to the same target host is needed for subsequent requests. HTTP代理还能够保持空闲链接活一段时间,以防止链接到同一个目标主机须要后续的请求。The ability to keep connections alive is usually refered to as connection persistence. 可以保持链接活着一般称为链接的持久性。HttpClient fully supports connection persistence.HttpClient彻底支持链接的持久性。react
2.2. 2.2。HTTP connection routingHTTP链接路由
HttpClient is capable of establishing connections to the target host either directly or via a route that may involve multiple intermediate connections - also referred to as hops. HttpClient可以创建链接到目标主机或直接或经过一个路线,可能涉及多个中间链接——也称为啤酒花。HttpClient differentiates connections of a route into plain, tunneled and layered. HttpClient的区分链接路线进入平原,隧道式和分层。The use of multiple intermediate proxies to tunnel connections to the target host is referred to as proxy chaining.使用多个中介代理隧道链接到目标主机称为代理连接。浏览器
Plain routes are established by connecting to the target or the first and only proxy. 平原路线创建了��接到目标或第一个也是惟一代理。Tunnelled routes are established by connecting to the first and tunnelling through a chain of proxies to the target. 创建了挖路线经过链接第一和隧道经过一连串的代理到目标。Routes without a proxy cannot be tunnelled. 路线没有代理不能挖。Layered routes are established by layering a protocol over an existing connection. 分层路由创建了分层协议在一个现有的链接。Protocols can only be layered over a tunnel to the target, or over a direct connection without proxies.协议只能在一个隧道的分层目标,或在没有代理直接链接。安全
2.2.1. 2.2.1。Route computation路线计算
The这个 RouteInfointerface represents information about a definitive route to a target host involving one or more intermediate steps or hops.接口描述信息的最终目标主机路由到一个涉及一个或多个中间步骤或跳。 HttpRouteis a concrete implementation of the是一个具体的实施 RouteInfo, which cannot be changed (is immutable).,这是不能改变的(是不可变的)。 HttpTrackeris a mutable是一个可变的 RouteInfoimplementation used internally by HttpClient to track the remaining hops to the ultimate route target.实现内部使用HttpClient跟踪剩下的啤酒花的终极目标。路线 HttpTrackercan be updated after a successful execution of the next hop towards the route target.能够更新成功后执行下一跳向目标的路线。 HttpRouteDirectoris a helper class that can be used to compute the next step in a route. 是一个helper类,可用于计算下一步在路线。This class is used internally by HttpClient.这类内部使用HttpClient。服务器
HttpRoutePlanneris an interface representing a strategy to compute a complete route to a given target based on the execution context. 是一个接口表明一个策略来计算一个完整的路线到一个给定的目标基于执行上下文。HttpClient ships with two defaultHttpClient附带两个默认 HttpRoutePlannerimplementations.实现。 SystemDefaultRoutePlanneris based on是基于 java.net.ProxySelector. 。By default, it will pick up the proxy settings of the JVM, either from system properties or from the browser running the application. 默认状况下,它将加快代理设置的JVM,要么从系统属性或从浏览器中运行应用程序。The这个 DefaultProxyRoutePlannerimplementation does not make use of any Java system properties, nor any system or browser proxy settings. 实现不使用任何Java系统属性,也没有任何系统或浏览器的代理设置。It always computes routes via the same default proxy.它老是计算路线经过相同的默认代理���网络
2.2.2. 2.2.2。Secure HTTP connections安全HTTP链接
HTTP connections can be considered secure if information transmitted between two connection endpoints cannot be read or tampered with by an unauthorized third party. HTTP链接能够被认为是安全的,若是信息传播的两个端点之间的链接不能读取或篡改被未经受权的第三方。The SSL/TLS protocol is the most widely used technique to ensure HTTP transport security. 这个SSL / TLS协议是最普遍使用的技术,确保HTTP传输安全。However, other encryption techniques could be employed as well. 然而,其余的加密技术也可使用。Usually, HTTP transport is layered over the SSL/TLS encrypted connection.一般,HTTP传输是分层的SSL / TLS加密链接。多线程
2.3. 2.3。HTTP connection managersHTTP链接经理
2.3.1. 2.3.1。Managed connections and connection managers托管链接和链接经理
HTTP connections are complex, stateful, thread-unsafe objects which need to be properly managed to function correctly. HTTP链接是复杂的,有状态的,线程不安全的物品须要进行适当的管理,功能正确。HTTP connections can only be used by one execution thread at a time. HTTP链接只能用于一个执行线程在一个时间。HttpClient employs a special entity to manage access to HTTP connections called HTTP connection manager and represented by the雇佣了一个特殊的实体HttpClient管理访问HTTP链接称为HTTP链接管理器和所表明的 HttpClientConnectionManagerinterface. 接口。The purpose of an HTTP connection manager is to serve as a factory for new HTTP connections, to manage life cycle of persistent connections and to synchronize access to persistent connections making sure that only one thread can have access to a connection at a time. 目的的一个HTTP链接管理器是做为工厂新的HTTP链接,管理生命周期的持久链接和同步访问持久链接确保一次只有一个线程能够访问一个链接在一个时间。Internally HTTP connection managers work with instances of在内部HTTP链接经理处理的实例 ManagedHttpClientConnectionacting as a proxy for a real connection that manages connection state and controls execution of I/O operations. 做为一个代理,一个真正的链接管理的链接状态和控制执行I / O操做。If a managed connection is released or get explicitly closed by its consumer the underyling connection gets detached from its proxy and is returned back to the manager. 若是一个托管链接释放或获得显式地关闭它的消费者的underyling链接获得超脱于代理和返回到经理。Even though the service consumer still holds a reference to the proxy instance, it is no longer able to execute any I/O operations or change the state of the real connection either intentionally or unintentionally.尽管服务消费者仍持有该代理实例,它再也不可以执行任何I / O操做或国家的真正的链接有意或无心地。并发
This is an example of acquiring a connection from a connection manager:这是一个例子,得到一个链接从链接管理器:app
HttpClientContext context = HttpClientContext.create();
HttpClientConnectionManager connMrg = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("localhost", 80));
// Request new connection. This can be a long process
ConnectionRequest connRequest = connMrg.requestConnection(route, null);
// Wait for connection up to 10 sec
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
try {
// If not open
if (!conn.isOpen()) {
// establish connection based on its route info
connMrg.connect(conn, route, 1000, context);
// and mark it as route complete
connMrg.routeComplete(conn, route, context);
}
// Do useful things with the connection.
} finally {
connMrg.releaseConnection(conn, null, 1, TimeUnit.MINUTES);
}
The connection request can be terminated prematurely by calling链接请求能够提早终止调用 ConnectionRequest#cancel()if necessary. 若是必要的。This will unblock the thread blocked in the这将开启线程阻塞的 ConnectionRequest#get()method.法。dom
2.3.2. 2.3.2。Simple connection manager简单的链接管理器
BasicHttpClientConnectionManageris a simple connection manager that maintains only one connection at a time. 是一个简单的链接管理器维护一次只有一个链接。Even though this class is thread-safe it ought to be used by one execution thread only.尽管这类是线程安全的,应该用一只执行线程。 BasicHttpClientConnectionManagerwill make an effort to reuse the connection for subsequent requests with the same route. 将努力重用链接的后续请求相同的路线。It will, however, close the existing connection and re-open it for the given route, if the route of the persistent connection does not match that of the connection request. 可是,它将关闭现有的链接和从新打开它为给定的路线,若是路线的持久链接不匹配的链接请求。If the connection has been already been allocated, then若是链接已经被分配,而后 java.lang.IllegalStateExceptionis thrown.抛出。
This connection manager implementation should be used inside an EJB container.这个链接管理器实现应该用在EJB容器。
2.3.3. 2.3.3。Pooling connection manager池链接管理器
PoolingHttpClientConnectionManageris a more complex implementation that manages a pool of client connections and is able to service connection requests from multiple execution threads. 是一个更复杂的实现,管理一个池的客户端链接,可以服务链接请求从多个执行线程。Connections are pooled on a per route basis. 链接池在每一个路由基础。
A request for a route for which the manager already has a persistent connection available in the pool will be serviced by leasing a connection from the pool rather than creating a brand new connection.
请求一个路线,经理已经持久链接池中的可用将租赁服务的链接池而不是建立一个全新的链接。
PoolingHttpClientConnectionManagermaintains a maximum limit of connections on a per route basis and in total. 维护一个最大限度上的链接路由基础和总计每。Per default this implementation will create no more than 2 concurrent connections per given route and no more 20 connections in total. 每违约这个实现将建立不超过2并发链接每一个给出的路线,没有更多的20链接总。For many real-world applications these limits may prove too constraining, especially if they use HTTP as a transport protocol for their services.对于许多实际应用这些限制多是太约束,尤为是若是他们使用HTTP做为传输协议为他们服务。
This example shows how the connection pool parameters can be adjusted:这个例子显示了如何链接池参数能够调整:
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("locahost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
2.3.4. 2.3.4。Connection manager shutdown链接管理器关闭
When an HttpClient instance is no longer needed and is about to go out of scope it is important to shut down its connection manager to ensure that all connections kept alive by the manager get closed and system resources allocated by those connections are released.当HttpClient实例再也不须要和即将走出范围是重要的关闭其链接管理器来确保全部链接却还在经理获得关闭,系统资源分配这些链接被释放。
CloseableHttpClient httpClient = <...>
httpClient.close();
2.4. 2.4。Multithreaded request execution多线程请求执行
When equipped with a pooling connection manager such as当配备一个池链接管理器等 PoolingClientConnectionManager, HttpClient can be used to execute multiple requests simultaneously using multiple threads of execution.,HttpClient能够用来执行多个请求同时使用多个执行线程。
The这个 PoolingClientConnectionManagerwill allocate connections based on its configuration. 将分配链接基于它的配置。If all connections for a given route have already been leased, a request for a connection will block until a connection is released back to the pool. 若是全部链接对于一个给定的路线已经被租用,请求一个链接将阻塞,直到一个链接被释放回池中。One can ensure the connection manager does not block indefinitely in the connection request operation by setting一个能够确保链接管理器不块无限期的链接请求操做经过设置 'http.conn-manager.timeout'to a positive value. 一个积极的价值。If the connection request cannot be serviced within the given time period若是链接请求不能在规定时间内维修周期 ConnectionPoolTimeoutExceptionwill be thrown.将会抛出。
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
// URIs to perform GETs on
String[] urisToGet = {
"http://www.domain1.com/",
"http://www.domain2.com/",
"http://www.domain3.com/",
"http://www.domain4.com/"
};
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
While而 HttpClientinstances are thread safe and can be shared between multiple threads of execution, it is highly recommended that each thread maintains its own dedicated instance of实例是线程安全的和能够执行多个线程之间共享,强烈建议每一个线程维护本身的专用的实例 HttpContext .
static class GetThread extends Thread {
private final CloseableHttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {
this.httpClient = httpClient;
this.context = HttpClientContext.create();
this.httpget = httpget;
}
@Override
public void run() {
try {
CloseableHttpResponse response = httpClient.execute(
httpget, context);
try {
HttpEntity entity = response.getEntity();
} finally {
response.close();
}
} catch (ClientProtocolException ex) {
// Handle protocol errors
} catch (IOException ex) {
// Handle I/O errors
}
}
}
2.5. 2.5。Connection eviction policy链接驱逐政策
One of the major shortcomings of the classic blocking I/O model is that the network socket can react to I/O events only when blocked in an I/O operation. 的一个主要缺点的经典阻塞I / O模型是网络套接字能够对I / O事件只有当封锁在一个I / O操做。When a connection is released back to the manager, it can be kept alive however it is unable to monitor the status of the socket and react to any I/O events. 当一个链接被从新释放到经理,它能够保持活着不过是没法监控状态的插座和应对任何I / O事件。If the connection gets closed on the server side, the client side connection is unable to detect the change in the connection state (and react appropriately by closing the socket on its end).若是链接被关闭在服务器端,客户端链接没法检测链接状态的变化(和适当反应经过关闭套接字在它的结束)。
HttpClient tries to mitigate the problem by testing whether the connection is 'stale', that is no longer valid because it was closed on the server side, prior to using the connection for executing an HTTP request. HttpClient试图缓解该问题经过测试链接是否“陈旧”,再也不是有效的,由于它在服务器端被关闭以前,使用链接来执行一个HTTP请求。The stale connection check is not 100% reliable and adds 10 to 30 ms overhead to each request execution. 陈腐的链接检查不是100%可靠和增长10到30 ms每一个请求执行开销。The only feasible solution that does not involve a one thread per socket model for idle connections is a dedicated monitor thread used to evict connections that are considered expired due to a long period of inactivity. 惟一可行的解决方案,不涉及一个线程每插座模型是一个专用的空闲链接监控线程用来驱逐被认为是过时的链接因为长时间的不活动。The monitor thread can periodically call按期监控线程能够调用 ClientConnectionManager#closeExpiredConnections()method to close all expired connections and evict closed connections from the pool. 方法来关闭全部过时的链接和驱逐关闭链接池。It can also optionally call它还能够可选地叫 ClientConnectionManager#closeIdleConnections()method to close all connections that have been idle over a given period of time.方法来关闭全部链接在闲置时间超过一个给定的一段时间。
public static class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
2.6. 2.6。Connection keep alive strategy链接保持活着的策略
The HTTP specification does not specify how long a persistent connection may be and should be kept alive. HTTP规范没有指定如何长持久链接可能和应该保持活着。Some HTTP servers use a non-standard一些HTTP服务器使用一个非标准 Keep-Aliveheader to communicate to the client the period of time in seconds they intend to keep the connection alive on the server side. 头交流到客户的时间在秒他们打算继续活着的链接在服务器端。HttpClient makes use of this information if available. 利用这种信息HttpClient若是可用。If the若是 Keep-Aliveheader is not present in the response, HttpClient assumes the connection can be kept alive indefinitely. 标题中不存在的反应,HttpClient假设链接能够存活下去。However, many HTTP servers in general use are configured to drop persistent connections after a certain period of inactivity in order to conserve system resources, quite often without informing the client. 然而,许多HTTP服务器配置通用降低持久链接在某个时间静止为了节省系统资源,每每没有通知客户。In case the default strategy turns out to be too optimistic, one may want to provide a custom keep-alive strategy.若是默认的策略证实过于乐观,你可能须要提供一个自定义的维生的策略。
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(NumberFormatException ignore) {
}
}
}
HttpHost target = (HttpHost) context.getAttribute(
HttpClientContext.HTTP_TARGET_HOST);
if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
// Keep alive for 5 seconds only
return 5 * 1000;
} else {
// otherwise keep alive for 30 seconds
return 30 * 1000;
}
}
};
CloseableHttpClient client = HttpClients.custom()
.setKeepAliveStrategy(myStrategy)
.build();
2.7. 2.7。Connection socket factories链接套接字工厂
HTTP connections make use of a利用HTTP链接 java.net.Socketobject internally to handle transmission of data across the wire. 对象内部的数据传输处理跨线。However they rely on the然而他们依赖 ConnectionSocketFactoryinterface to create, initialize and connect sockets. 接口来建立、初始化和链接套接字。This enables the users of HttpClient to provide application specific socket initialization code at runtime.这使得用户提供应用程序特定的套接字HttpClient在运行时初始化代码。 PlainConnectionSocketFactoryis the default factory for creating and initializing plain (unencrypted) sockets.是默认的工厂来建立和初始化平原(加密)套接字。
The process of creating a socket and that of connecting it to a host are decoupled, so that the socket could be closed while being blocked in the connect operation.建立一个套接字的过程和链接到主机是解耦的,这样可能会关闭套接字在被封锁在链接操做。
HttpClientContext clientContext = HttpClientContext.create();
PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
Socket socket = sf.createSocket(clientContext);
int timeout = 1000; //ms
HttpHost target = new HttpHost("localhost");
InetSocketAddress remoteAddress = new InetSocketAddress(
InetAddress.getByAddress(new byte[] {127,0,0,1}), 80);
sf.connectSocket(timeout, socket, target, remoteAddress, null, clientContext);
2.7.1. 2 7 1。Secure socket layering安全套接字层
LayeredConnectionSocketFactoryis an extension of the是一个扩展的 ConnectionSocketFactoryinterface. 接口。Layered socket factories are capable of creating sockets layered over an existing plain socket. 分层的套接字工厂有能力建立套接字分层在现有的普通插座。Socket layering is used primarily for creating secure sockets through proxies. 套接字层主要用于建立安全插座经过代理。HttpClient ships withHttpClient附带 SSLSocketFactorythat implements SSL/TLS layering. 实现SSL / TLS分层。Please note HttpClient does not use any custom encryption functionality. 请注意HttpClient不使用任何自定义的加密功能。It is fully reliant on standard Java Cryptography (JCE) and Secure Sockets (JSEE) extensions.它是彻底依赖于标准的Java加密(JCE)和安全套接字(JSEE)扩展。
2.7.2. 2 7 2。Integration with connection manager集成和链接管理器
Custom connection socket factories can be associated with a particular protocol scheme as as HTTP or HTTPS and then used to create a custom connection manager.自定义链接套接字工厂能够关联到一个特定的协议方案做为做为HTTP或HTTPS,而后用来建立一个自定义的链接管理器。
ConnectionSocketFactory plainsf = <...>
LayeredConnectionSocketFactory sslsf = <...>
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainsf)
.register("https", sslsf)
.build();
HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
HttpClients.custom()
.setConnectionManager(cm)
.build();
2.7.3. 2 7 3。SSL/TLS customizationSSL / TLS定制
HttpClient makes use of SSLSocketFactory to create SSL connections.HttpClient利用SSLSocketFactory建立SSL链接。 SSLSocketFactoryallows for a high degree of customization. 容许一个高程度的定制。It can take an instance of它能够采起的一个实例 javax.net.ssl.SSLContextas a parameter and use it to create custom configured SSL connections.做为一个参数,并使用它来建立自定义配置SSL链接。
HttpClientContext clientContext = HttpClientContext.create();
KeyStore myTrustStore = <...>
SSLContext sslContext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(myTrustStore)
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
Customization of SSLSocketFactory implies a certain degree of familiarity with the concepts of the SSL/TLS protocol, a detailed explanation of which is out of scope for this document. 定制的SSLSocketFactory意味着必定程度的熟悉的概念SSL / TLS协议,详细解释这是超出了本文的范围文档。Please refer to the请参考Java Secure Socket ExtensionJava安全套接字扩展for a detailed description of详细描述的 javax.net.ssl.SSLContextand related tools.和相关工具。
2.7.4. 2 7 4。Hostname verification主机名验证
In addition to the trust verification and the client authentication performed on the SSL/TLS protocol level, HttpClient can optionally verify whether the target hostname matches the names stored inside the server's X.除了信任验证和客户端身份验证上执行SSL / TLS协议级别,HttpClient能够验证目标主机是否匹配名称存储在服务器的X。509 certificate, once the connection has been established. 509证书,一旦链接已经创建。This verification can provide additional guarantees of authenticity of the server trust material. 这个验证能够提供额外的真实性保证服务器的信任材料。The这个 X509HostnameVerifierinterface represents a strategy for hostname verification. 接口表明一个策略验证主机名。HttpClient ships with threeHttpClient附带三个 X509HostnameVerifierimplementations. 实现。Important: hostname verification should not be confused with SSL trust verification.重要:主机名验证不该混淆SSL信任验证。
StrictHostnameVerifier: The strict hostname verifier works the same way as Sun Java 1.4, Sun Java 5, Sun Java 6. 严格的主机名校验工做同样Sun Java 1.4,Sun Java 5,Sun Java 6。It's also pretty close to IE6. 它也是很是接近IE6。This implementation appears to be compliant with RFC 2818 for dealing with wildcards. 这个实现彷佛符合RFC 2818处理通配符。The hostname must match either the first CN, or any of the subject-alts. 主机名必须匹配要么第一CN,或任何主题高���。A wildcard can occur in the CN, and in any of the subject-alts.一个通配符能够发生在CN,和在任何学科高分。
BrowserCompatHostnameVerifier: This hostname verifier that works the same way as Curl and Firefox. 这个主机名验证器,做品同样卷曲和Firefox。The hostname must match either the first CN, or any of the subject-alts. 主机名必须匹配要么第一CN,或任何主题高分。A wildcard can occur in the CN, and in any of the subject-alts. 一个通配符能够发生在CN,和在任何学科高分。The only difference between惟一的区别 BrowserCompatHostnameVerifierand和 StrictHostnameVerifieris that a wildcard (such as "*.foo.com") with是一个通配符(如“* .foo.com”) BrowserCompatHostnameVerifiermatches all subdomains, including "a.b.foo.com".匹配全部子域,包括“a.b.foo.com”。
AllowAllHostnameVerifier: This hostname verifier essentially turns hostname verification off. This implementation is a no-op, and never throws这个主机名校验其实主机名验证关闭。实现是一个空操做,从不抛出 javax.net.ssl.SSLException.
Per default HttpClient uses the默认使用HttpClient BrowserCompatHostnameVerifierimplementation. 实现。One can specify a different hostname verifier implementation if desired一个能够指定一个不一样的主机名若是须要校验的实现
SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
2.8. 2.8。HttpClient proxy configurationHttpClient代理配置
Even though HttpClient is aware of complex routing scemes and proxy chaining, it supports only simple direct or one hop proxy connections out of the box.尽管HttpClient知道复杂的路由scemes和���理连接,它只支持简单的直接的或单跳代理链接的盒子。
The simplest way to tell HttpClient to connect to the target host via a proxy is by setting the default proxy parameter:最简单的方法告诉HttpClient链接到目标主机经过代理是经过设置默认代理参数:
HttpHost proxy = new HttpHost("someproxy", 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
One can also instruct HttpClient to use the standard JRE proxy selector to obtain proxy information:一我的也能够指导HttpClient使用标准JRE代理选择器来获取代理信息:
SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(
ProxySelector.getDefault());
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
Alternatively, one can provide a custom另外,一个能够提供一个自定义的 RoutePlannerimplementation in order to have a complete control over the process of HTTP route computation:实现为了有一个完整的控制过程的HTTP路径计算:
HttpRoutePlanner routePlanner = new HttpRoutePlanner() {
public HttpRoute determineRoute(
HttpHost target,
HttpRequest request,
HttpContext context) throws HttpException {
return new HttpRoute(target, null, new HttpHost("someproxy", 8080),
"https".equalsIgnoreCase(target.getSchemeName()));
}
};
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
}
}
---------------------
做者:简单ai
来源:CSDN
原文:https://blog.csdn.net/bushijieinside/article/details/12314689
版权声明:本文为博主原创文章,转载请附上博文连接!