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 );
}
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.
I ran into same problem when using emulator, because I changed wifi on my laptop so restarting the wifi of emulator solved my problem.
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.
If you open a VPN, "Unknown host exception" may be the result
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
Ok, I feel pretty lame... The INTERNET permission tag is a child of the manifest tag, not the application tag. Sheesh!