Android的HttpURLConnection的速度很慢(Android HttpURLConn

2019-09-21 14:24发布

这是我面临着下面的代码的情况:

正如你可以看到我试图读取HTTP流。 当我运行在Android模拟器下面的代码它工作时间的100%,当我运行在我的Galaxy S3下面的代码,而在3G它工作时间的100%,当我尝试使用我的笔记本电脑连接到URL浏览器,它的工作原理的100%的时间,当我尝试使用Galaxy S3的浏览器(在WiFi和3G)连接它的工作原理......时间的100%。 然而,当我尝试使用Wi-Fi网络时我我的Galaxy S3,而外出连接的〜80%的时间。 如果我删除了超时属性我得到奇怪的例外,如:

"recvfrom failed: ETIMEDOUT"
"failed to connect to <URL>: connect failed: ENETUNREACH (Network is unreachable)"
"unable to resolve the host <URL>: no address associated with hostname"

我愿意接受任何建议...

public static final String getHttpResponse(String url)
{
    HttpURLConnection conn = null;
    InputStream response = null;
    try { 
        URL address = new URL(url);
        conn = (HttpURLConnection)address.openConnection();
        conn.setConnectTimeout(30 * 1000); //30 seconds
        conn.setReadTimeout(30 * 1000); //30 seconds

        response = conn.getInputStream();

        if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 
            Log.e("Util.getHttpResponse", Integer.toString(conn.getResponseCode()));
            return null; 
        }

        String result = Util.streamToString(response);
        return result;

    } catch(IOException e) {
        response = conn.getErrorStream();
        Log.e("Util.getHttpResponse", Util.streamToString(response));
        return null;

    } finally { 
        if( response != null ) { 
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn != null) { 
            conn.disconnect();
        }
    }
}

更新: - 使用AndroidHttpClient没有工作 - 让输入流我有一个错误弹出权在Eclipse IDE中......之后你可以看到我的调试光标使它一路线路107 ..好后,我做得到输入流这段时间...

Answer 1:

我的Android设备上同样的问题。 我在URL中使用的IP地址。 最后,我发现HttpURLConnection.connect(...)方法涉及的gethostname()内部。 在那之后,我使用站点的URL,然后它工作时间的100%。



Answer 2:

作为一个实验,如果你尝试使用AndroidHttpClient类,而不是做同样的? 它有一些预定义的超时和其他设置,我们被告知,在大多数情况下正常工作。



文章来源: Android HttpURLConnection VERY slow