简体   繁体   中英

Android HttpURLConnection VERY slow

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... 日食

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM