Android: UnknownHostException

2019-01-08 13:35发布

I am using Android SDK 2.2, testing my application with the emulator. I want to send a HTTP Post. When I do I get a UnknownHostException. I have placed the required permissions
<uses-permission android:name="android.permission.INTERNET" />
in the manifest.xml. Also I can open the browser on the emulator and navigate to the URL with no problem.

Here is my code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost( uri );
HttpResponse response = null;
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2 );
nameValuePairs.add( new BasicNameValuePair( "id", "edit-name" ) );
nameValuePairs
.add( new BasicNameValuePair( "stringdata", userName ) );
httppost.setEntity( new UrlEncodedFormEntity( nameValuePairs ) );

// Execute HTTP Post Request
response = httpclient.execute( httppost );
// Log.i( "HttpManager:", "======> response: "
// + response.getEntity().getContent() );

}
catch (ClientProtocolException e)
{
Log.e( "HttpManager", "ClientProtocolException thrown" + e );
}
catch (IOException e)
{
Log.e( "HttpManager", "IOException thrown" + e );
}

14条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-08 13:40

I ran into a similar problem when testing an app that had a minSdkVersion set to 4 and I was trying to run it on a G1. Changing it to 3 solved the problem for me.

查看更多
戒情不戒烟
3楼-- · 2019-01-08 13:41

I ran into same problem when using emulator, because I changed wifi on my laptop so restarting the wifi of emulator solved my problem.

查看更多
孤傲高冷的网名
4楼-- · 2019-01-08 13:43

If none of the above worked, try taking a step back and making sure that your device or emulator can actually reach the internet by opening up a browser.

查看更多
家丑人穷心不美
5楼-- · 2019-01-08 13:43

If you open a VPN, "Unknown host exception" may be the result

查看更多
6楼-- · 2019-01-08 13:50

One other thing: It turned out that the internet itself wasn't working for me. Launching the emulator from the commandline with these switches fixed it for me: emulator -avd your_avd_name -dns-server 8.8.8.8

查看更多
一夜七次
7楼-- · 2019-01-08 13:52

Ok, I feel pretty lame... The INTERNET permission tag is a child of the manifest tag, not the application tag. Sheesh!

查看更多
登录 后发表回答