尝试将网页作为字符串读取,这是我的代码:
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)