如何解决如果使用主机名代替IP地址,则会在Android应用程序中引发UnknownHostException
|| 我有以下代码,用于将请求发送到服务器。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();
}
当我在模拟器上运行程序时,我在行上收到UnKnownHostException
response = httpclient.execute(httppost);
如果我直接使用ip地址而不是主机名,则请求发送正确。
请注意以下几点:
我正在使用Android 2.3.3
我在清单xml中添加了“ 2”
代理设置在仿真器的APN中更新。
使用模拟器中的浏览器,我可以访问带有其主机名的网站。
知道为什么这会引起问题吗?
解决方法
请确保您遵循了user700284问题中所述的所有步骤1-4。
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\");
,网址与该行无关
se = new StringEntity(inputXML,HTTP.UTF_8);
您确定是这条线吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。