UnknownHostException is thrown in android app if hostname is used instead of IP address
I have the following code which I use to send a request to the server.
String inputXML = createInputXML(searchText);
HttpClient httpclient = new DefaultHttpClient();
String url = "http://mysite.com/action";//Works fine if I use IP address directly,for eg:http://1.2.3.4/action
HttpPost httppost = new HttpPost(url);
HttpResponse response=null;
StringEntity se = null;
try {
se = new StringEntity(inputXML, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/xml;charset=UTF-8");
httppost.setEntity(se);
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I run the program on emulator I am getting a UnKnownHostException on the line
response = httpclient.execute(httppost);
If I use the ip address directly instead of host name,the request is sent correctly. Please note the following points:
- I am using Android 2.3.3
- I have added
<uses-permission android:name="android.perm开发者_运维百科ission.INTERNET"></uses-permission>
in the manifest xml - Proxy settings are updated in the emulator's APN.
- Using the browser in the emulator I can access a website with their host names.
Any idea why this is causing an issue?
Please make sure, you followed all steps 1-4 user700284 described in his Question.
HttpClient client = new DefaultHttpClient();
//Get the default settings from APN (could be also hard coded stuff)
String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
//Set Proxy params of client, if they are not the standard
if (proxyHost != null && proxyPort > 0) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpGet request = new HttpGet("http://www.google.com");
The url has nothing to do with the line
se = new StringEntity(inputXML, HTTP.UTF_8);
are you sure it is this line?
精彩评论