我有以下代码用于向服务器发送请求。
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
- 我已经添加了
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
在 list xml 中 - 代理设置在模拟器的 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");
关于android - 如果使用主机名而不是 IP 地址,Android 应用程序将抛出 UnknownHostException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6096706/