HttpClient Tutorial (ii)

Source: Internet
Author: User
Tags httpcontext ssl connection

Chapter II Connection Management

The httpclient has a complete control over the connection initialization and termination, as well as I/O operations on the active connection. Many aspects of the connection operation can be controlled using some parameters.

2.1 Connection Parameters

These parameters can affect the connection operation:

  • ' Http.socket.timeout ': Defines the millisecond time-out of the socket (so_timeout), which is the maximum idle time between two consecutive packets waiting for data, in other words. If the time-out is 0, it is interpreted as an infinitely large time-out. This parameter expects to get a value of type Java.lang.Integer. If this parameter is not set, then the read operation will not time out (infinite timeout).
  • ' Http.tcp.nodelay ': Determines whether the Nagle algorithm is used. The Nagle algorithm view saves bandwidth by minimizing the number of packets sent. When applications want to reduce network latency and improve performance, they can turn off the Nagle algorithm (that is, turn on tcp_nodelay). Data will be sent earlier, adding to the documented bandwidth consumption. This parameter expects to get a value of type Java.lang.Boolean. If this parameter is not set, then the Tcp_nodelay is turned on (no delay).
  • ' Http.socket.buffer-size ': Determines the size of the internal socket buffer used to buffer the data while receiving/transmitting HTTP messages. This parameter expects to get a value of type Java.lang.Integer. If this parameter is not set, then HttpClient will allocate a 8192-byte socket cache.
  • ' Http.socket.linger ': Set So_linger with a specified number of seconds to delay. The maximum connection timeout value is specified by the platform. A value of 0 implies that this option is turned off. A value of 1 implies that the JRE is used by default. This setting only affects the socket close operation. If this parameter is not set, then it is assumed that the value is-1 (JRE default).
  • ' Http.connection.timeout ': Determines the millisecond time-out period until the connection is established. A value of 0 for the timeout period is interpreted as an infinitely large time. This parameter expects to get a value of type Java.lang.Integer. If this parameter is not set, the connection operation will not time out (unlimited timeout).
  • ' Http.connection.stalecheck ': Determines whether to use the old connection check. When a request is executed on top of a connection and the server-side connection is closed, shutting down the old connection check may result in a significant performance gain when the risk of an I/O error is attained (the check time can be 30 milliseconds for each request). This parameter expects to get a value of type Java.lang.Boolean. For performance-critical operations, the check should be turned off. If this parameter is not set, then the old connection will be executed before each request executes.
  • ' Http.connection.max-line-length ': Determines the limit of the maximum requested length. If set to a positive number, any HTTP request lines exceeding this limit will throw an java.io.IOException exception. A negative number or 0 will close this check. This parameter expects to get a value of type Java.lang.Integer. If this parameter is not set, then the restriction is not enforced.
  • ' Http.connection.max-header-count ': Determines the maximum number of HTTP header information allowed. If set to a positive number, the amount of HTTP header information obtained from the data stream exceeds this limit and throws an Java.io.IOException exception. A negative number or 0 will close this check. This parameter expects to get a value of type Java.lang.Integer. If this parameter is not set, then it is not
  • The restrictions are enforced.
  • ' Http.connection.max-status-line-garbage ': Determines the maximum number of request lines that can be ignored before an HTTP response status line is expected to be received. With http/1.1 persistent connection, this problem produces a broken script that will return an incorrect content-length (there is more send than the specified byte). Unfortunately, in some cases, this cannot be detected later in the error response, only until the next time. So HttpClient had to skip those extra rows in this way. This parameter expects to get a value of type Java.lang.Integer. 0 is all garbage/blank lines that are not allowed before the status line. Use Java.lang.integer#max_value to set unlimited numbers. If this parameter is not set then it is assumed to be unrestricted.
2.2 Persistent connections

The process of establishing a connection from one host to another is quite complex, and it is quite time-consuming to include the exchange of many packets between the two terminals. The overhead of connecting a handshake is important, especially for a small amount of HTTP messages. If an open connection can be reused to perform multiple requests, then high data throughput can be achieved.

http/1.1 emphasizes that HTTP connections can be re-used for multiple requests by default. http/1.0-compatible terminals can also use similar mechanisms to explicitly communicate their preferences to ensure that the connection is active and use it to process multiple requests. The HTTP proxy can also keep an idle connection active for a period of time, preventing a connection to the same target host that might be required for subsequent requests. The ability to maintain connection activity is often referred to as a persistent connection. HttpClient fully supports persistent connections.

2.3 HTTP Connection Routing

HttpClient is able to establish a connection to the target host either directly or through a route, which involves multiple intermediate connections, also known as hops. HttpClient differentiate between routing and normal connections, channels, and hierarchies. The use of multiple intermediary proxies that are connected to a destination host is also known as a proxy chain.

A normal route is created by a proxy that connects to the target or only the first time. Channel routing is established through the proxy chain to the destination connection to the first channel. Routes that do not have a proxy are not channels, and layered routing is established through a layered protocol that already exists for the connection. The protocol can be layered only on the channel to the target or on a direct connection without a proxy.

2.3.1 Routing Calculation

The Routeinfo interface represents information about the destination host route that ultimately involves one or more intermediate steps or jumps. Httproute is the concrete implementation of routeinfo, which cannot be changed (is unchanged). Httptracker is a mutable routeinfo implementation that is used internally by HttpClient to track the remaining hops to the maximum routing target. The Httptracker can be updated after a successful execution of the next hop to the routing target. Httproutedirector is a helper class that can be used to calculate the next hop in a route. This class is used internally by HttpClient.

Httprouteplanner is an interface that represents the evaluation of a full routing policy based on the execution context to a given target. The httpclient comes with two default Httprouteplanner implementations. Proxyselectorrouteplanner is based on the java.net.ProxySelector. By default, it picks the JVM's proxy settings from the system properties or from the browser running the application. The Defaulthttprouteplanner implementation does not use any Java System Properties, nor does it use the system or browser proxy settings. It calculates the route based on HTTP only, as described in the following parameters.

2.3.2 Secure HTTP Connection

If the information is transferred between two terminals that cannot be read or modified by a non-authenticated third party, the HTTP connection can be considered secure. The SSL/TLS protocol is the most widely used technology to ensure the security of HTTP transmissions. Other encryption techniques can also be used. Typically, HTTP transports are layered on top of SSL/TLS encrypted connections.

2.4 HTTP Routing parameters These parameters can affect routing calculations:
    • ' Http.route.default-proxy ': Defines a proxy host that can be used by a default routing planner that is not provisioned with the JRE. This parameter expects to get a value of type Httphost. If this parameter is not set, it will attempt to connect directly to the target.
    • ' Http.route.local-address ': Defines a local address to be used by all default routing planners. In a machine with multiple network interfaces, this parameter can be used to select a network interface from the connection source. This parameter expects to get a value of type java.net.InetAddress. If this parameter is not set, the local address will be used automatically.
    • ' Http.route.forced-route ': Defines a mandatory route that is used by all default route planners. Instead of calculating the route, the given forced route will be returned, although it points to a completely different target host. This parameter expects to get a value of type Httproute. If this parameter is not set, the connection to the target server is established using the default rule.
2.5 Socket Factory

Layeredsocketfactory is an extension of the Socketfactory interface. A layered socket factory can use the Java.net.Socket object inside an HTTP connection to handle the transmission of data over the wire. They rely on the Socketfactory interface to create, initialize, and connect sockets. This makes it possible for httpclient users to provide applications that specify socket initialization code at run time. Plainsocketfactory is the default factory for creating and initializing generic (unencrypted) sockets.

The process of creating sockets and the process of connecting to the host are not right, so sockets can be closed when the connection operation is blocked.

plainsocketfactory SF = Plainsocketfactory.getsocketfactory (); Socket socket = Sf.createsocket (); Httpparams params = new Basichttpparams ();p arams.setparameter (Coreconnectionpnames.connection_timeout, 1000L); Sf.connectsocket (socket, "locahost", 8080, null,-1, params);
2.5.1 Secure Sockets tiering

Layeredsocketfactory is an extension of the Socketfactory interface. A layered socket factory can create a layered socket on top of an already existing normal socket. Socket hierarchies create Secure sockets primarily through proxies. The httpclient comes with a sslsocketfactory that implements SSL/TLS tiering. Note that httpclient does not use any of the custom encryption features. It relies entirely on standard Java Cryptography (JCE) and Secure Sockets (Jsee) extensions.

2.5.2 SSL/TLS customization

HttpClient uses Sslsocketfactory to create an SSL connection. Sslsocketfactory allows highly customizable. It can use an instance of Javax.net.ssl.SSLContext as an argument and use it to create a custom SSL connection.

TrustManager Easytrustmanager = new X509trustmanager () {@Overridepublic void checkclienttrusted ( X509certificate[] chain,string authtype) throws Certificateexception {//Oh, that's easy! } @Overridepublic void checkservertrusted (x509certificate[] chain,string authtype) throws Certificateexception {//Oh, It's simple! } @Overridepublic x509certificate[] Getacceptedissuers () {return null;}}; Sslcontext Sslcontext = sslcontext.getinstance ("TLS") Sslcontext.init (null, new trustmanager[] {Easytrustmanager}, NULL); Sslsocketfactory SF = new Sslsocketfactory (sslcontext); Sslsocket socket = (sslsocket) sf.createsocket () socket.setenabledciphersuites (new string[] {"ssl_rsa_with_rc4_128_ MD5 "}); Httpparams params = new Basichttpparams ();p arams.setparameter (Coreconnectionpnames.connection_timeout, 1000L); Sf.connectsocket (socket, "locahost", 443, NULL,-1, params);
Sslsocketfactory's customization implies familiarity with the concept of a certain degree of SSL/TLS protocol, a detailed explanation beyond the scope of this document. Refer to the Java Secure Sockets extension [http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html], This is a detailed description of the Javax.net.ssl.SSLContext and related tools. 2.5.3 hostname Verification In addition to trust authentication and client authentication at the SSL/TLS protocol level, once the connection is established, httpclient can optionally verify that the target hostname matches the name stored in the server's "nine" certificate. This certification can provide a true guarantee of additional server trust materials. The X509 hostname authentication interface represents the policy for host name validation. The httpclient comes with 3 X509 host name validators. It is important to note that host name validation should not confuse SSL trust authentication.
    • Stricthostnameverifier: Strict hostname validation is the same in Sun Java 1.4,sun java 5 and Sun Java 6. And it's very close to IE6. This implementation appears to be compatible with RFC 2818 to handle wildcards. The host name must match the first CN or any of the subject-alt. Wildcard characters may appear in the CN and any other subject-alt.
    • Browsercompathostnameverifier: the hostname validator and Curl and Firefox work the same way. The host name must match the first CN or any of the subject-alt. Wildcard characters may appear in the CN and any other subject-alt. The only difference between Browsercompathostnameverifier and Stricthostnameverifier is a wildcard character that uses Browsercompathostnameverifier to match all subdomains (such as "*". Foo.com "), including" a.b.foo.com ".
    • Allowallhostnameverifier: This hostname validator is basically shutting down the host name verification. This implementation is an empty operation and does not throw a javax.net.ssl.SSLException exception.

Each of the default httpclient uses the Browsercompathostnameverifier implementation. It can specify a different host name validator implementation, if needed.

sslsocketfactory SF = new Sslsocketfactory (sslcontext.getinstance ("TLS")); Sf.sethostnameverifier ( Sslsocketfactory.strict_hostname_verifier);
2.6 Protocol Mode

The scheme class represents a protocol pattern, such as "http" or "https", which also contains some protocol properties, such as the default port, which is used to create a socket factory for a java.net.Socket instance of a given protocol. The Schemeregistry class is used to maintain a set of scheme, and when it goes through the request URI to establish a connection, httpclient can choose from:

Scheme http = new Scheme ("http", Plainsocketfactory.getsocketfactory (), 80); Sslsocketfactory SF = new Sslsocketfactory (sslcontext.getinstance ("TLS")); Sf.sethostnameverifier ( Sslsocketfactory.strict_hostname_verifier); Scheme HTTPS = new scheme ("https", SF, 443); schemeregistry sr = new Schemeregistry (); Sr.register (HTTP); Sr.register (HTTPS);
2.7 HttpClient proxy configuration

Although HttpClient understands complex routing patterns and proxy chains, it only supports simple direct or out-of-box hop proxy connections.

The simplest way to tell HttpClient to connect to a target host through a proxy is by setting the default proxy parameters:

defaulthttpclient httpclient = new Defaulthttpclient (); Httphost proxy = new Httphost ("Someproxy", 8080); Httpclient.getparams (). Setparameter (Connroutepnames.default_proxy, proxy);

You can also build httpclient to use the standard JRE proxy selector to obtain proxy information:

defaulthttpclient httpclient = new Defaulthttpclient (); Proxyselectorrouteplanner Routeplanner = new Proxyselectorrouteplanner (Httpclient.getconnectionmanager (). Getschemeregistry (), Proxyselector.getdefault ()); Httpclient.setrouteplanner (Routeplanner);

Another option is to provide a custom routeplanner implementation to get complex control over HTTP routing computation processing:

defaulthttpclient httpclient = new Defaulthttpclient (); Httpclient.setrouteplanner (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 ()));});
2.8 HTTP Connection Manager 2.8.1 connection operator

A connection operation is a low-level socket for a client or a connection that can be manipulated by an external entity, often called a connection operation. The Operatedclientconnection interface extends the Httpclientconnection interface and defines additional methods for controlling connection sockets. The Clientconnectionoperator interface represents a policy for creating instances and updating those object low-level sockets. The implementation class is most likely to use Socketfactory to create java.net.Socket instances. The Clientconnectionoperator interface allows httpclient users to provide a custom strategy for connection operations and the ability to provide an optional implementation of the Operatedclientconnection interface.

2.8.2 managing connections and connection managers

HTTP connections are complex, stateful, thread-insecure objects that require proper management to perform functions correctly. An HTTP connection can only be used by one execution thread at a time. HttpClient uses a special entity to manage the access HTTP connection, which is called the HTTP Connection Manager and represents the Clientconnectionmanager interface. The purpose of an HTTP connection manager is to serve as a factory for new HTTP connections, to manage persistent connections and to synchronize access to persistent connections to ensure that only one thread at a time can access a connection.

The internal HTTP Connection Manager works with Operatedclientconnection instances, but they provide an instance of the service consumption managedclientconnection. Managedclientconnection plays the wrapper on the Operatedclientconnection instance that controls all I/O operations above the management State control. It also abstracts the socket operation, providing a convenient way to open and update to create a routing socket. Managedclientconnection instances understand the links that produce them to the Connection manager and, based on this fact, they must be returned to the manager when they are no longer in use. The Managedclientconnection class also implements the Connectionreleasetrigger interface, which can be used to trigger the release of a connection back to the manager. Once the release connection operation is triggered, the wrapped connection is detached from the Managedclientconnection wrapper and the Operatedclientconnection instance is returned to the manager. Although the service consumer still holds a reference to the Managedclientconnection instance, it no longer performs any I/O operations or operatedclientconnection state that is unintentionally altered.

Here is an example of getting a connection from the Connection manager:

httpparams params = new Basichttpparams (); Scheme http = new Scheme ("http", Plainsocketfactory.getsocketfactory (), 80); schemeregistry sr = new Schemeregistry (); Sr.register (HTTP); Clientconnectionmanager CONNMRG = new Singleclientconnmanager (params, SR);//Request a connection. This can be a very long process. Clientconnectionrequest connrequest = connmrg.requestconnection (new Httproute (New Httphost ("localhost"), null); /wait to connect for 10 seconds managedclientconnection conn = connrequest.getconnection (timeunit.seconds); try {//Use the connection to do something useful. Releases the connection when it is complete. Conn.releaseconnection ();} catch (IOException ex) {//Terminates the connection on the I/O error. Conn.abortconnection (); throw ex;}

If necessary, the connection request can be prematurely interrupted by a call to the Clientconnectionrequest#abortrequest () method. This unlocks the blocked thread in the Clientconnectionrequest#getconnection () method.

Once the response is completely consumed, the Basicmanagedentity wrapper class can be used to ensure that the lower-level connections are automatically released. This mechanism is used internally by HttpClient to transparently release the connection for all responses obtained from the Httpclient#execute () method:

clientconnectionrequest connrequest = connmrg.requestconnection (new Httproute ("localhost", 80)), NULL); Managedclientconnection conn = Connrequest.getconnection (ten, timeunit.seconds); try {basichttprequest request = new Basichttprequest ("GET", "/"); Conn.sendrequestheader (request); HttpResponse response = Conn.receiveresponseheader (); conn.receiveresponseentity (response); httpentity entity = response.getentity (), if (entity! = null) {basicmanagedentity managedentity = new Basicmanagedentity (E Ntity, Conn, true);//Replace entity response.setentity (managedentity);} Use the response object to do something useful. This connection is automatically freed when the response content is consumed. } catch (IOException ex) {//Terminates the connection on the I/O error. Conn.abortconnection (); throw ex;}
2.8.3 Simple Connection Manager

Singleclientconnmanager is a simple connection manager, at the same time it only maintains a connection. Although this class is thread-safe, it should be used for one thread of execution. Singleclientconnmanager will reuse connections as much as possible for subsequent requests on the same road. If the persistent connection route does not match the connection request, it also closes the existing connection and then opens a new one for the given route. If the connection is already assigned, a Java.lang.IllegalStateException exception will be thrown.

For each default connection, HttpClient uses Singleclientconnmanager.

2.8.4 Connection pool Manager

Threadsafeclientconnmanager is a complex implementation to manage client connection pooling, and it can also service connection requests from multiple threads of execution. For each basic route, the connection is managed by the pool. For a routed request, the manager has a persistent connection available in the pool and will be leased from the pool to the connection service instead of creating a new connection.

The Threadsafeclientconnmanager maintains the maximum connection limit for each basic route. Each default implementation will create a concurrent connection of no more than two for each given route, and no more than 20 connections in total. For many real-world applications, this limitation also proves a big constraint, especially when they use HTTP as the transport protocol in the service. Connection restrictions, or you can use the HTTP parameter to adjust.

This example shows how the connection pool parameters are adjusted:

httpparams params = new Basichttpparams ();//increase maximum connection to 200connmanagerparams.setmaxtotalconnections (params, 200);// Increase the default maximum connection per route to 20ConnPerRouteBean Connperroute = new Connperroutebean (20);//increase the maximum connection to the localhost:80 to 50HttpHost localhost = new Httphost ("Locahost"), Connperroute.setmaxforroute (new Httproute (localhost), 50); Connmanagerparams.setmaxconnectionsperroute (params, connperroute); Schemeregistry schemeregistry = new Schemeregistry (); Schemeregistry.register (New Scheme ("http", Plainsocketfactory.getsocketfactory (), Schemeregistry.register ("https", Sslsocketfactory.getsocketfactory (), 443)); Clientconnectionmanager cm = new Threadsafeclientconnmanager (params, schemeregistry); HttpClient HttpClient = new Defaulthttpclient (cm, params);
2.8.5 Connection Manager shutdown

When a httpclient instance is no longer needed and is about to go out of use, it is important to close the Connection manager to ensure that all connections maintained by the manager are closed and that the system resources allocated by the connection are freed.

defaulthttpclient httpclient = new Defaulthttpclient (); HttpGet httpget = new HttpGet ("http://www.google.com/"); HttpResponse response = Httpclient.execute (HttpGet); httpentity entity = response.getentity (); System.out.println (Response.getstatusline ()); if (entity! = null) {entity.consumecontent ();} Httpclient.getconnectionmanager (). Shutdown ();
2.9 Connection management parameters These are parameters that can be used to customize the implementation of the standard HTTP connection manager:
    • ' Http.conn-manager.timeout ': Defines the millisecond-level time-out that is used when retrieving managedclientconnection instances from Clientconnectionmanager. This parameter expects to get a value of type Java.lang.Long. If this parameter is not set, the connection request does not time out (unlimited timeout).
    • ' Http.conn-manager.max-per-route ': Defines the maximum number of connections per route. This restriction is interpreted by the client Connection Manager and is applied to stand-alone manager instances. This parameter expects to get a value of type Connperroute.
    • ' Http.conn-manager.max-total ': Defines the maximum number of total connections. This restriction is interpreted by the client Connection Manager and is applied to stand-alone manager instances. This parameter expects to get a value of type Java.lang.Integer.
2.1 Multi-Threaded execution requests

When equipped with a connection pool manager, such as threadsafeclientconnmanager,httpclient can be used to execute multiple requests simultaneously, using multi-threaded execution.

The Threadsafeclientconnmanager will be assigned a connection based on its configuration. If all connections to a given route are leased, the connected request will be blocked until a connection is freed back to the connection pool. It is possible to ensure that the connection manager does not block indefinitely when the connection request executes by setting ' Http.conn-manager.timeout ' as a positive number. If the connection request cannot be responded to within a given time period, a Connectionpooltimeoutexception exception will be thrown.

httpparams params = new Basichttpparams (); Schemeregistry schemeregistry = new Schemeregistry (); Schemeregistry.register (New Scheme ("http", Plainsocketfactory.getsocketfactory (), 80)); Clientconnectionmanager cm = new Threadsafeclientconnmanager (params, schemeregistry); HttpClient HttpClient = new Defaulthttpclient (cm, params);//Execute Get method uristring[] 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 (urist Oget[i]); Threads[i] = new GetThread (httpClient, httpget);}
//Start execution thread for (int j = 0; J < Threads.length; J + +) {Threads[j].start ();} Merge thread for (int j = 0; J < Threads.length; J + +) {threads[j].join ();} static class GetThread extends Thread {private fin Al HttpClient httpclient;private final HttpContext context;private final HttpGet httpget;public GetThread (HttpClient HttpClient, HttpGet httpget) {this.httpclient = Httpclient;this.context = new Basichttpcontext (); this.httpget = HttpGet;} @Overridepublic void Run () {try {HttpResponse response = This.httpClient.execute (This.httpget, This.context); httpentity entity = response.getentity (); if (entity! = NULL) {//do something useful to the entity ...//ensure that the connection can be released back to the manager entity.consumecontent ();}} catch (Exception ex) {This.httpget.abort ();}}}
2.11 Connection Retract policy

A major disadvantage of a classic blocking I/O model is that network sockets can respond to I/O events only when I/O operations are blocked. When a connection is released back to the manager, it can be kept alive without monitoring the status of the socket and responding to any I/O events. If the connection is closed on the server side, then the client connection is not able to detect changes in the status of the connection and close the socket on this side to make an appropriate response.

HttpClient attempts to mitigate this problem by testing whether the connection is outdated, which is no longer valid because it is already closed on the server side, before using the connection that executed the HTTP request. Outdated connection checking is not 100% stable, but adds 10 to 30 milliseconds of overhead per request execution. The only feasible socket model threading solution that does not involve each pair of idle connections is to use a dedicated monitoring thread to reclaim connections that are considered to be out of date because of long inactivity. The monitoring thread can periodically invoke the Clientconnectionmanager#closeexpiredconnections () method to close all expired connections and retract closed connections from the connection pool. It can optionally call the Clientconnectionmanager#closeidleconnections () method to close all connections that have been idle for a given period of time.

Public
Static Class Idleconnectionmonitorthread extends Thread {private final Clientconnectionmanager Connmgr;priva Te volatile boolean shutdown;public idleconnectionmonitorthread (Clientconnectionmanager connmgr) {super (); This.connmgr = Connmgr;} @Overridepublic void Run () {try {while (!shutdown) {synchronized (this) {Wait (5000);// Close expired connection connmgr.closeexpiredconnections ();//Optionally, turn off idle for more than 30 seconds Connection connmgr.closeidleconnections (timeunit.seconds);}} catch (Interruptedexception ex) {//terminates}}public void shutdown () {shutdown = true;synchronized (this) {Notifyall ();}}}
2.12 Connecting policies to keep active

The HTTP specification does not determine how long a persistent connection might or should remain active. Some HTTP servers use nonstandard header information keep-alive to tell clients how many seconds they want to keep the connection activity on the server side. If this information is available, httclient will use it. If the header information keep-alive does not exist in the response, HttpClient assumes that the connection remains active indefinitely. However, many real-world HTTP servers are configured to discard persistent connections after a specific inactive period to conserve system resources, often without notifying the client. If the default policy proves overly optimistic, someone will want to provide a custom retention strategy.

Defaulthttpclient httpclient = new Defaulthttpclient (); Httpclient.setkeepalivestrategy (new Connectionkeepalivestrategy () {public long getkeepaliveduration (httpresponse response, HttpContext context) {//cashing ' Keep-alive ' header information 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 (executioncontext.http_ Target_host), if ("www.naughty-server.com". Equalsignorecase (Target.gethostname ())) {//Only keep active 5 seconds return 5 *;} else {/ /Otherwise keep active 30 seconds return 30 * 1000;}});

HttpClient Tutorial (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.