-2

尝试将网页作为字符串读取,这是我的代码:

    public class ReadWebPage extends Activity {
private EditText url_text;
private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    url_text = (EditText) findViewById(R.id.address);
    textView = (TextView) findViewById(R.id.tv);
}
public void myButtonClickHandler(View view) {
    switch (view.getId()) {
    case R.id.ReadWebPage:
        try {
            if (!url_text.getText().toString().trim().equalsIgnoreCase("")) {
                textView.setText("");
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet(url_text.getText().toString());
                // Get the response
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String response_str = client.execute(request,
                        responseHandler);
                textView.setText(response_str);
            } else {
                Toast.makeText(getApplicationContext(),
                        "URL String empty.", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            System.out.println("Some error occured.");
            textView.setText(e.getMessage());
        }
        break;
    }
}
    }

如上所述,我使用该代码显示我的代码并尝试将某些网页读取为字符串,但它显示该错误。

  03-03 22:37:45.088: I/System.out(1233): Some error occured.
   03-03 22:37:45.088: W/System.err(1233): android.os.NetworkOnMainThreadException
  03-03 22:37:45.138: W/System.err(1233):   at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)    org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
 -03 22:37:45.148: W/System.err(1233):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
  03-03 22:37:45.158: W/System.err(1233):   at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
4

1 回答 1

0

Android 告诉你你不应该在 UI 线程上进行网络操作。它不希望您阻塞线程,这是有充分理由的。

尝试改用AsyncTask。将您的 HTTP 请求代码放入doInBackground()方法中并更新方法TextView中的onPostExecute()。您不能从该doInBackground()方法访问 UI 线程。

这是一个非常基本的示例:

class MyAsyncTask extends AsyncTask<String, String, String> 
{
    private TextView textView;

    public MyAsyncTask(TextView textView)
    {
        this.textView = textView;
    }

    protected Long doInBackground(String... params) 
    {
        String url = params[0];
        // your HTTP request code goes here
        return response;
    }

    protected void onPostExecute(String result) 
    {
        textView.setText(result);
    }
}

像这样使用类:

new MyAsyncTask(myTextView).execute(myUrl);
于 2013-03-03T17:19:02.963 回答