Persistent HttpURLConnections on Android

最后都变了- 提交于 2019-12-03 08:57:12

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!