如何从android中的网站url获取html文本?

时间:2011-07-04 11:59:40

标签: android

public class TestProjMain extends Activity {
/** Called when the activity is first created. */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final EditText eText = (EditText) findViewById(R.id.address);
        final TextView tView = (TextView) findViewById(R.id.pagetext);


        final Button button = (Button) findViewById(R.id.ButtonGo);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                try {
                    tView.setText("");
                // Perform action on click
                    URL url = new URL(/*"http://www.google.com"*/eText.getText().toString());
                    URLConnection conn = url.openConnection();
                    // Get the response
                    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {


                        tView.append(line);
                    }
                }
                catch (Exception e) {
                }
            }
        });        
    }
}

我写了这个,但它不起作用。我也使用了httpclient代码,但也没有用。每次执行此函数时,我的模拟器都会停止响应。我不知道问题在哪里?有人请帮忙!提前谢谢......

2 个答案:

答案 0 :(得分:3)

最好使用AsyncTask进行网络通话。

使用AsyncTask的方法如下:

  1. 在doInBackground()方法中,写下以下代码:

    URL url = new URL(/*"http://www.google.com"*/eText.getText().toString());
    URLConnection conn = url.openConnection();
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    
  2. 在onPostExecute()方法中,编写显示代码:

            while ((line = rd.readLine()) != null) {
    
    
                tView.append(line);
            }
    

答案 1 :(得分:0)

使用像这样的asynctask

public class RetrieveSiteData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
    StringBuilder builder = new StringBuilder(16384);

    DefaultHttpClient client = new DefaultHttpClient();

    HttpGet httpGet = new HttpGet(urls[0]);

    try {
        HttpResponse execute = client.execute(httpGet);
        InputStream content = execute.getEntity().getContent();

        BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
        String s = "";
        while ((s = buffer.readLine()) != null) {
            builder.append(s);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


    return builder.toString();
}

@Override
protected void onPostExecute(String result) {

}

}