android - 如果使用主机名而不是 IP 地址,Android 应用程序将抛出 UnknownHostException

标签 android android-emulator

我有以下代码用于向服务器发送请求。

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 地址而不是主机名,请求将被正确发送。 请注意以下几点:

  1. 我使用的是 Android 2.3.3
  2. 我已经添加了<uses-permission android:name="android.permission.INTERNET"></uses-permission>在 list xml 中
  3. 代理设置在模拟器的 APN 中更新。
  4. 使用模拟器中的浏览器,我可以使用他们的主机名访问网站。

知道为什么这会导致问题吗?

最佳答案

请确保您遵循了 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/

相关文章:

java - 如何在 ChromeDriver 使用 Appium 和 Android Studio 上禁用保存密码

android - 模拟器总是启动而不是设备

android - React Native map 编译错误 debugJavaWithJavac

java - 重复类 org.apache.commons.logging

android - 位置管理器接近警报或地理围栏

android - 从 firebase 数据库获取数据时显示进度对话框

android - 由于找不到 FileProvider 类,在模拟器上重新安装后应用程序崩溃

java - 由于以下原因导致Android Studio崩溃:java.lang.ArrayIndexOutOfBoundsException:length = 1;指数= 6

java - 多种 Activity 中的 ButterKnife

android - 如何在android中压缩和解压缩png图像