在Android上持续HttpURLConnectionsAndroid、HttpURLConnections

2023-09-05 04:54:23 作者:浅爱

我有一个问题,试图让Android应用程序(当然,服务,它区分这有什么差别),使用持续的HTTP 1.1连接。

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.

下面的循环(简化的测试案例)工程通过在桌面JRE一个TCP会话,但在整个socket建立/拆除周期的Andr​​oid设备的结果。

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();

            } catch (MalformedURLException e) {
            } catch (IOException e) {
            }       
        }

甲骨文的JDK介绍了一种叫做系统属性:

The Oracle's JDK describes something called 'system properties':

http.keepAlive =   默认值:true

http.keepAlive= default: true

http.maxConnections =   默认值:5

http.maxConnections= default: 5

有没有在Android的运行类似的起价维持p $ pvents持久连接东西?

Is there something similar in Android's runtime that prevents persistent connections from being maintained?

推荐答案

Android的JVM使用Apache的HTTP组件库引擎盖HTTP连接下(甚至包括那些使用java.net接口都做到了):这样的行为是微妙的不同从Oracle JVM。

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.

在理论上潜在的和谐code尊重 http.keepAlive 系统属性,但这种行为是否谷歌的副本preserves不肯定我。

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.

。这是漫长而痛苦的,但如果你看看的http:// hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html 它概述了HTTP组件的连接管理办法。请看第2.11节详细介绍了如何使用HTTP组件显式控制连接管理。

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.

祝你好运。

 
精彩推荐
图片推荐