2012-08-24 204 views
1

這就是我面臨的情況,下面的代碼:Android HttpURLConnection非常慢

正如你所看到的,我試圖讀取一個HTTP流。當我在Android模擬器上運行以下代碼時,100%的時間工作,當我在Galaxy S3上運行以下代碼時,它在100%的時間內運行,當我嘗試使用筆記本電腦連接到URL時瀏覽器它100%的時間工作,當我嘗試連接使用銀河S3瀏覽器(無論是在WiFi和3G),它的工作... 100%的時間。但是,當我嘗試使用我的Galaxy S3在Wi-Fi上連接時,我超時〜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行..以及我完成後獲得輸入流... Eclipse

回答

0

作爲一個實驗,如果您嘗試使用AndroidHttpClient類代替它做同樣的事情會怎麼樣?它有一些預定義的超時時間和其他設置,我們被告知,在大多數情況下應該可以正常工作。

+0

謝謝,我會給出一個答案並回復。不過,我嘗試使用org.apache.http.client.HttpClient並得到相同的結果。 – Cailen

1

我在Android設備上遇到了同樣的問題。我在URL中使用IP地址。最後,我發現HttpURLConnection.connect(...)方法在內部涉及getHostName()。之後,我使用網址中的域名,然後在100%的時間內運行。