我正在通过这个程序尝试一个简单的http连接,但是获得了resourcenotfoundexception,无法解析主机“www.google.com”:没有与hostname相关的地址。这背后的原因是什么?
public class HttpClientActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
// .permitAll().build();
// StrictMode.setThreadPolicy(policy);
// connect();
new Connection().execute();
}
private class Connection extends AsyncTask {
@Override
protected Object doInBackground(Object... arg0) {
connect();
return null;
}
}
private void connect() {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com");
HttpResponse response = client.execute(request);
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
答案 0 :(得分:2)
请确认您可以通过自己的APP访问互联网。
该权限在AndroidManifest.xml
中定义。
确保您拥有以下权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
编辑如果仍然无法使用,请尝试使用此代码
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000);
urlc.connect();
Log.i(Tag,Integer.toString(urlc.getResponseCode()));