HttpClient学习研究---第二章:连接管理
第二章。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.人能达到一个更高的数据吞吐量如果打开的连接可以被重用来执行多个请求。
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完全支持连接的持久性。
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:这是一个例子,获得一个连接从连接管理器:
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.法。
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
版权声明:本文为博主原创文章,转载请附上博文链接!
https://jinnianshilongnian.iteye.com/blog/2089792