2012-09-07 54 views
0

我想從網頁獲取HTML,但我不能。這裏是我的代碼從Android中獲取Html來自網絡

final EditText et = (EditText) findViewById(R.id.editText1); 
    final TextView tv = (TextView) findViewById(R.id.textView1); 
    final Button b = (Button) findViewById(R.id.button1); 
    b.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 

      try { 
       URL url = null; 
       url = new URL(et.getText().toString()); 
       URLConnection conn = url.openConnection(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        tv.append(line); 

       } 
      } catch (Exception e) { 
       Log.e("error", "erorr connection "+ e.toString()); 
      }    
     } 
    }); 

我也加入了來自互聯網的許可。目標版本4.0.3

+0

我想從網站獲取HTML以顯示在文本視圖 – kongkea

+0

http://stackoverflow.com/questions/6466719/manipulating-data-on-webs-in-android/6466749#6466749 – Rasel

+0

解決方法是在這裏http:// stackoverflow.com/questions/12327625/error-when-get-html-from-web-in-android/12328074#12328074 –

回答

1

請把網絡部件到後臺線程,然後更新到前臺UI線程。您可以使用AsyncTask來執行此操作。

3

//創建HTTP客戶端

HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet("http:// yoururl"); 
    HttpResponse response = httpclient.execute(httpget); 
    HttpEntity entity = response.getEntity(); 
    InputStream is = entity.getContent(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) 
     sb.append(line + "\n"); 

    String resString = sb.toString(); // Result is here 

    is.close(); // Close the stream