2012-07-18 162 views
0

我正在製作一個Android應用程序,爲此我必須從URL(由一些python腳本輸出)獲取JSON內容。閱讀網頁內容,獲取異常

我在SO上找到了一個方法,但是我無法讓它工作。這是代碼:

public String webGet(String URL) throws Exception 
{ 
    BufferedReader in = null; 
    try 
    { 
     HttpClient client = new DefaultHttpClient(); 
     client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android"); 

     HttpGet request = new HttpGet(); 
     request.setHeader("Content-Type", "text/html; charset=utf-8"); 
     request.setURI(new URI(URL)); 

     // Crashes after executing this line 
     HttpResponse response = client.execute(request); 

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

     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 

     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) 
     { 
      sb.append(line + NL); 
     } 
     in.close(); 
     String page = sb.toString(); 

     //System.out.println(page); 
     return page; 
    } 
    finally 
    { 
     if (in != null) 
     { 
      try 
      { 
       in.close(); 
      } 
      catch (IOException e)  
      { 
       Log.d("BBB", e.toString()); 
      } 
     } 
    } 
} 

這墜毀行後happends:

HttpResponse response = client.execute(request); 

它後來乾脆跳到finally部分和所有我可以從異常消息得到的是某事是null。這就是它所說的。

任何人都知道問題可能是什麼?


截圖異常說明:

enter image description here

+0

什麼是完整的異常消息? – 2012-07-18 12:47:56

+0

@Vakimshaar添加了錯誤截圖 – w00 2012-07-18 12:55:18

+0

您仍然看不到整個堆棧跟蹤 – 2012-07-18 12:58:51

回答

0

您不能執行某些Android版本中從「主線程」的網絡行動。這是爲了確保您的應用程序仍能夠響應最終用戶,即使它執行了一些需要很長時間的阻止網絡操作。

你需要做那個動作的另一個線程。

Unable to connect to FTP in Android