I've got an issue trying to get the Android application (well, Service, it case it makes any difference) to use persistent HTTP 1.1 connections.
The following loop (simplified test case) works through a single TCP session on a desktop JRE, but on an Android device results in the whole socket creation/teardown cycle.
while (true) {
URL url;
try {
url = new URL("http://10.0.0.125:8080/SRV?");
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
开发者_JAVA百科} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
The Oracle's JDK describes something called 'system properties':
http.keepAlive= default: true
http.maxConnections= default: 5
Is there something similar in Android's runtime that prevents persistent connections from being maintained?
Android's JVM uses the Apache HTTP Components library under the hood for HTTP connections (even those that are done using the java.net interface): as such the behavior is subtly different from the Oracle JVM.
In theory the underlying Harmony code respects the http.keepAlive
system property, but whether Google's copy preserves that behavior isn't certain to me.
If you want to be absolutely certain what's happening you have to use the HttpComponents code. It is long and painful, but if you look at http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html it outlines the connection management approach for http components. Look at section 2.11 which details how to explicitly control the connection management using HTTP components.
Good luck.
I was seeing the same issue with persistent HTTP 1.1 connections not being established. I wrote a quick test app to obtain more details.
First I performed a TCP dump of traffic from my app to see what was happening. "Connection:keep-alive" is being sent properly to my server. My server was then responding with "Connection:keep-alive". However after my app closed its connection's InputStream, the underlying socket was closed by Android as well...instead of being persisted.
To dig deeper, I wrote my app to connect using two different approaches:
HttpURLConnection con = (HttpURLConnection) url.openConnection();
AND
HttpClient client = new DefaultHttpClient();
It turn out that HttpClient was not persisting the underlying sockets but HttpURLConnection does. So if you want the best performance, use HttpURLConnections until Android resolves this bug in DefaultHttpClient.
Seems like a bug in Android HTTP 1.1 implementation?
精彩评论