2013-04-11 86 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