我有以下代码:
protected void testConnection(String url) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responsehandler = new BasicResponseHandler();
try {
String connection = httpclient.execute(httpget, responsehandler);
Toast.makeText(getBaseContext(), R.string.connection_succeed, Toast.LENGTH_SHORT).show();
view_result.setText(connection);
} catch(IOException e) {
Toast.makeText(getBaseContext(), R.string.connection_failed, Toast.LENGTH_SHORT).show();
}
httpclient.getConnectionManager().shutdown();
}
并在Manifest中添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
但是它抛出了一个异常: NetworkOnMainThreadException, 我该怎么办?
NetworkOnMainThreadException
的帖子吧。它解释了为什么会发生这种情况。 - Alex Lockwood