Android HttpURLConnection VERY slow

喜欢而已 提交于 2019-12-08 05:08:31

问题


This is the situation I'm facing with the code below:

As you can see I'm trying to read an HTTP stream. When I run the following code on the Android simulator it works 100% of the time, when I run the following code on my Galaxy S3 while on 3G it works 100% of the time, when I try to connect to the URL using my laptop browser it works 100% of the time, when I try to connect using the Galaxy S3 browser (in both wifi and 3g) it works... 100% of the time. HOWEVER, when I try to connect using my Galaxy S3 while on Wi-Fi I time out ~80% of the time. If I remove the timeout properties I get weird exceptions such as:

"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"

I'm open to any suggestions...

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

UPDATE: - using AndroidHttpClient did not work - After getting the input stream I had an error popup right in the eclipse IDE... As you can see my debug cursor made it all the way to line 107.. well after I was done getting the input stream this time...


回答1:


I got the same problem on Android device. I use an IP address in the url. Final, I found the HttpURLConnection.connect(...) method involved the getHostName() internally. After that, I use the domain in the url, then it works 100% of the time.




回答2:


As an experiment, what if you try using AndroidHttpClient class instead for doing the same? It has some predefined timeouts and other settings which, we were told, should work fine in most cases.



来源:https://stackoverflow.com/questions/12108166/android-httpurlconnection-very-slow

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