2013-04-11 88 views
0

我正在開發一個Android應用程序,它將採取網頁的源代碼,然後解析它。Android設備無法連接到網頁與HttpURLConnection

只要我的設備連接到它開發的電腦上,我就可以得到這個工作,但是,當我試圖從pc斷開連接時,它似乎無法檢索信息。有人可以告訴我我做錯了什麼嗎?

要通過的AsyncTask讓我用下面的代碼的源代碼:

private String downloadUrl(String myurl) throws IOException { 
    InputStream is = null; 

    try { 
     URL url     = new URL(myurl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(20000 /* milliseconds */); 
     conn.setConnectTimeout(25000 /* milliseconds */); 
     conn.setRequestMethod("GET"); 
     conn.setDoInput(true); 

     // Starts the query 
     conn.connect(); 
     response = conn.getResponseCode(); 
     Log.d(DEBUG_TAG, "The response is: " + response); 

     if (response == 200) { 

      is = conn.getInputStream(); 

      BufferedReader buffer = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); 

      // Convert the InputStream into a string 
      String s = ""; 
      while ((s = buffer.readLine()) != null) { 
       myTextView.append(s); 
       myTextView.append("\n"); 

      } 

      conn.disconnect(); 
      is.close(); 
      return myTextView.getText().toString(); 
     } else { 
      conn.disconnect(); 
      return ""; 
     } 


    } finally { 
     if (is != null) { 
      is.close(); 

     } 
    } 
} 
+1

不知道這是否會幫助,但你不必調用'連接()',一旦你被稱爲'的openConnection()' – 2013-04-11 09:21:27

+0

@Haelty我是否需要關閉和我一樣的連接?我試圖在發佈模式下運行它,但手機不會連接。 – Nick 2013-04-11 09:46:16

+0

是的,最好關閉連接;)但是你可以在'finally'塊中調用它,以便在任何情況下調用它(即使之前調用了「return」)。 – 2013-04-11 09:49:29

回答

1

好像在我的調用的AsyncTask下面一行是保持設備等待計算機連接。

android.os.Debug.waitForDebugger(); 
+0

這是什麼意思?在調試模式下,應用程序尚未等待調試器? :P – 2013-04-11 11:15:22

+0

不,它不會停止在由AsyncTask調用的代碼中,因爲它在不同的線程上,請參閱[本答案](http://stackoverflow.com/a/4770967/1620085)。 – Nick 2013-04-11 11:28:15