2011-06-14 45 views
0

我正在嘗試編寫一些代碼,這些代碼需要從用戶獲取一個網址,然後當點擊提交按鈕後,我將接收網址並撥打電話從頁面檢索html源代碼。不過,我已經得到了以下的例外:在Android應用程序中獲取帶有網址的html源代碼

W/System.err的(14858):android.os.NetworkOnMainThreadException W/System.err的(14858):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork( StrictMode.java:1077)

看來,對於Android 3.0我試圖開發的平臺不允許我使用主要方法上的網絡資源。我知道有一些方法,比如在後臺運行它,或者使用async方法應該可以工作,但是任何人都可以在這方面指導我嗎?我不太確定如何去做。我是編程新手。 在此先感謝。

下面是我當前的代碼上的onclick方法:

String htmlCode = ""; 

    try { 
    URL url = new URL("http://www.google.com"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

    String inputLine; 

    while ((inputLine = in.readLine()) != null) { 
     htmlCode += inputLine; 
     Log.d(LOG_TAG, "html: " + inputLine); 
    } 

    in.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     Log.d(LOG_TAG, "Error: " + e.getMessage()); 
     Log.d(LOG_TAG, "HTML CODE: " + htmlCode); 
    } 

回答

1

你可以使用一個Runnable或線程,但可能是最地道的Android方式做到這一點是使用的AsyncTask。

new AsyncTask<String, Void, String>(){ 
    @Override 
    protected String doInBackground(String... urlStr){ 
    // do stuff on non-UI thread 
    StringBuffer htmlCode = new StringBuffer(); 
    try{ 
     URL url = new URL(urlStr[0]); 
     BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

     String inputLine; 

     while ((inputLine = in.readLine()) != null) { 
     htmlCode += inputLine; 
     Log.d(LOG_TAG, "html: " + inputLine); 
     } 

     in.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     Log.d(LOG_TAG, "Error: " + e.getMessage()); 
     Log.d(LOG_TAG, "HTML CODE: " + htmlCode); 
    } 
    return htmlCode.toString(); 
    }   

    @Override 
    protected void onPostExecute(String htmlCode){ 
    // do stuff on UI thread with the html 
    TextView out = (TextView) findViewById(R.id.out); 
    out.setText(htmlCode); 
    } 
}.execute("http://www.google.com");