2013-04-26 56 views
-4

下面是完整的方法。它以String的形式返回給定URL的HTML代碼。 經過一定的測試後,我得出了try塊被跳過的結論。但我不知道爲什麼。Java中的異常處理有什麼問題

public static String getHtml(String url) 
{ 
    StringBuilder result = new StringBuilder(); 
    try { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpGet httpGet = new HttpGet(url); 
     HttpResponse response = httpClient.execute(httpGet, localContext); 


     BufferedReader reader = new BufferedReader(
      new InputStreamReader(
       response.getEntity().getContent() 
      ) 
      ); 

     String line = null; 
     char c = '"'; //The Java complains about this type of char So I removed it from the source. 
     while ((line = reader.readLine()) != null){ 
      for(int i = line.length()-1; i >0; --i){ 
       if (line.charAt(i) != c){ 
        result.append(line); 
       } 
      } 
     } 
     return result.toString(); 
    } catch(Exception e){ 
      result.append("<p><img src=http://desperateshadows.files.wordpress.com/2013/02/img_0721.jpg?w=730 class=size-full alt=Green green not evergreen /></p><p>Little flower at a glance</p>"); //A test Source 

     return result.toString(); 
    } 



} 
+0

第一:不要 「吃」 的例外。在返回結果之前調用'e.printStacktrace();'。第二:從logcat發佈stacktrace。您是否還有在AndroidManifest.xml中添加Internet權限? – Darwind 2013-04-26 10:05:47

+0

你的日誌貓顯示什麼。? – SilentKiller 2013-04-26 10:06:09

+3

你怎麼知道它被跳過? – Asahi 2013-04-26 10:06:22

回答

0

您正在從UI線程調用execute()。自Android 3.0+以後,禁止在UI線程上運行阻止操作。

0

請在Android的manifest.xml上網放許可

<manifest xlmns:android...> ... 
    <application android:label="@string/app_name" >... 
    </application>  
    <uses-permission android:name="android.permission.INTERNET"></uses-permission> 
</manifest>