第二章。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
版權聲明:本文爲博主原創文章,轉載請附上博文連接!