HttpClient Network optimization
Although the Android website recommends using HttpURLConnection as the preferred class for networking development in 2.3 and later versions, HttpClient still has a big advantage in connection management and thread safety. For now, HttpClient is still a choice to consider. For httpclient optimization, you can start with the following:
(1) using a singleton mode (reusing httpclient instances)
For a communication unit or even an entire application, Apache strongly recommends using only one instance of HttpClient. For example:
private static HttpClient HttpClient = Null
private static synchronized HttpClient gethttpclient () {
if (httpClient = = null) {
final Httpparams httpparams = new Basichttpparams ();
HttpClient = new Defaulthttpclient (httpparams);
}
return HttpClient;
}
(2) Stay connected (reuse connection)
for applications that already have a connection to the server, it is not necessary to re-establish a new connection when calling httpclient for network data transfer, but to reuse the established connection. This will undoubtedly reduce overhead and increase speed.
In this respect, Apache has done "connection management", and by default, it will reuse existing connections as much as possible, so no client programmer is required to do any configuration. Just be aware that Apache's connection management does not actively release established connections, requiring programmers to manually close the connection when not in use.
(3) Multi-threaded security management configuration
If your application uses multithreading for network access, you should manage it with the Apache encapsulated thread-safe management class Threadsafeclientconnmanager, which will enable more efficient and more secure management of connections in multi-threaded and connection pools.
(on the internet also saw someone using Multithreadedhttpconnectionmanager for thread safety management, and then checked the next Apache API, Multithreadedhttpconnectionmanager is found to be a class in API 2.0, and Threadsafeclientconnmanager is the class in API 4.0, newer than the former, So choose to use Threadsafeclientconnmanager. In addition, you see that there are Poolingclientconnectionmanager classes, which are classes in API 4.2, that are newer than Threadsafeclientconnmanager, but that class is not found in the Android SDK. So I chose Threadsafeclientconnmanager to manage it now.
For example:
Clientconnectionmanager manager = new Threadsafeclientconnmanager (Httpparams, schemeregistry);
HttpClient = new Defaulthttpclient (manager, Httpparams);
(4) How to use "Request flow/Response flow" when transferring data in large quantities
When you need to transfer large amounts of data, you should not use a string (strings) or byte array (byte arrays) because they cache the data into memory. When there is too much data, especially in multithreaded situations, memory overflow can easily be caused (out of memory,oom).
and httpclient can effectively handle "stream." These "streams" are not cached to memory, but are transmitted directly. The use of a "request flow/Response Flow" approach to transport can reduce memory consumption and reduce the risk of memory overflow.
For example:
Get method: Getresponsebodyasstream ()
Not use Getresponsebody (), or getresponsebodyasstring ()
GetMethod httpget = new GetMethod (URL);
InputStream InputStream = Httpget.getresponsebodyasstream ();
Post method: Getresponsebodyasstream ()
Postmethod HttpPost = new Postmethod (URL);
InputStream InputStream = Httppost.getresponsebodyasstream ();
(5) Continuous handshake (expect-continue handshake)
In the case of authentication systems or other cases where the server refuses to respond (for example, a login failure), it can significantly reduce the efficiency if the entire request body is sent. At this point, you can send a partial request (for example: Send only the request header) for heuristics, and if the server is willing to receive, continue to send the request body. This optimization is mainly configured as follows:
Use expect-continue handshake
Httpprotocolparams.setuseexpectcontinue (Httpparams, true);
httpclient in order to improve performance, the default uses a "reuse connection" mechanism, that is, when there is a transfer of data requirements, the connection pool is first checked for reuse of the connection, if any, the connection will be reused. At the same time, to ensure that the "reused" connection is actually valid, it is checked for validity before reuse. This check will take about 15-30 milliseconds. Turning this check off will slightly increase the transfer speed, but it may also be that the "old connection" is too long and the server side shuts down, resulting in I/O exceptions.
turn off old connection check configuration to:
//disable stale check
Httpconnectionparams.setstalecheckingenabled (Httpparams, false);
(7) Timeout setting
time-out setting to allow the connection to expire automatically after a time, freeing up resource usage.
//Timeout:get connections from connection pool
Connmanagerparams.settimeout (Httpparams, +);
//Timeout:connect to the server
httpconnectionparams.setconnectiontimeout (Httpparams, default_socket_timeout);
//Timeout:transfer data from server
httpconnectionparams.setsotimeout ( Httpparams, default_socket_timeout);
(8) Limit of connections
Configure the maximum number of connections per host and the maximum connections in the connection pool to limit the number of connections. Of these, default_host_connections and Default_max_connections are set by the client programmer as needed.
Set Max connections per host
Connmanagerparams.setmaxconnectionsperroute (Httpparams, New Connperroutebean (default_host_connections));
Set Max Total connections
Connmanagerparams.setmaxtotalconnections (Httpparams, default_max_connections);
After optimization, the Gethttpclient () method code in the previous log is as follows:
[Java]View Plaincopy
- Private static synchronized HttpClient gethttpclient () {
- if (httpClient = = null) {
- final Httpparams httpparams = new Basichttpparams ();
- //Timeout:get connections from connection pool
- Connmanagerparams.settimeout (Httpparams, 1000);
- //Timeout:connect to the server
- Httpconnectionparams.setconnectiontimeout (Httpparams, default_socket_timeout);
- //Timeout:transfer data from server
- Httpconnectionparams.setsotimeout (Httpparams, default_socket_timeout);
- //Set Max connections per host
- Connmanagerparams.setmaxconnectionsperroute (Httpparams, new Connperroutebean (default_host_connections));
- //Set Max Total connections
- Connmanagerparams.setmaxtotalconnections (Httpparams, default_max_connections);
- //Use expect-continue handshake
- Httpprotocolparams.setuseexpectcontinue (Httpparams, true);
- //disable stale check
- Httpconnectionparams.setstalecheckingenabled (Httpparams, false);
- Httpprotocolparams.setversion (Httpparams, httpversion.http_1_1);
- Httpprotocolparams.setcontentcharset (Httpparams, HTTP. UTF_8);
- Httpclientparams.setredirecting (Httpparams, false);
- //Set User agent
- String useragent = "mozilla/5.0 (Windows; U Windows NT 5.1; ZH-CN; rv:1.9.2) gecko/20100115 firefox/3.6 ";
- Httpprotocolparams.setuseragent (Httpparams, useragent);
- //disable Nagle algorithm
- Httpconnectionparams.settcpnodelay (Httpparams, true);
- Httpconnectionparams.setsocketbuffersize (Httpparams, default_socket_buffer_size);
- //Scheme:http and HTTPS
- Schemeregistry schemeregistry = new Schemeregistry ();
- Schemeregistry.register (new Scheme ("http", Plainsocketfactory.getsocketfactory (), 80));
- Schemeregistry.register (new Scheme ("https", Sslsocketfactory.getsocketfactory (), 443));
- Clientconnectionmanager manager = new Threadsafeclientconnmanager (Httpparams, schemeregistry);
- HttpClient = New Defaulthttpclient (manager, Httpparams);
- }
- return httpClient;
- }
Appendix: On the optimization of HttpURLConnection, the online information is not much. See a little from the Android official online, organized as follows:
(1) When uploading data to the server (that is, sending a request to the server), if you know the size of the uploaded data, you should explicitly use Setfixedlengthstreamingmode (int) to set the exact value of the uploaded data, if you do not know the size of the uploaded data, You should use Setchunkedstreamingmode (int)-typically passed in as the actual parameter using the default value of "0". If none of the two functions are set, the system forces all content in the request body to be cached in memory (before transmission over the network), wasting "heap" memory (and possibly even draining it) and aggravating the pitfalls.
(2) If you enter or output a small amount of data through a stream, you need to use a stream with a buffer (such as Bufferedinputstream), and when you read or output data in large quantities, you can ignore the buffered stream (the disk I/O is increased without using a buffered stream, and the default stream operation is directly disk i/ O's);
(3) When a large amount of data needs to be transmitted (input or output), use "flow" to limit the amount of data in memory-that is, to place the data directly in the "stream" rather than in a byte array or string (these are stored in memory).
Reference article:
Http://hc.apache.org/httpclient-3.x/performance.html
http://blog.csdn.net/androidzhaoxiaogang/article/details/8198400
http://guowww.diandian.com/post/2011-11-07/15351973
http://blog.csdn.net/ken831001/article/details/7925309
http://www.iteye.com/topic/1117362
http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/tsccm/ Threadsafeclientconnmanager.html
http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/ Poolingclientconnectionmanager.html
HttpClient Network optimization