2011-05-23 42 views
2

我有下面的代码用于向服务器发送请求。如果使用主机名而不是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(); 
} 

当我在模拟器上运行该程序,我上线

response = httpclient.execute(httppost);

得到一个的UnknownHostException如果我使用的IP地址,而不是直接的主机名,请求被发送正确的。 请注意以下几点:

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

任何想法为什么这会导致问题?

+0

您是否找到针对您的问题的解决方案?这真的可以帮助我。我有完全相同的问题(APN设置最新,android2.3.3,权限设置,浏览器工作) – 2012-02-16 00:32:23

+0

不幸的是,没有... :( – user700284 2012-02-16 05:16:56

+0

我现在找到了答案,可以从APN代理设置设备并使用它们不幸的是,我的项目在我办公室的另一台计算机上,但明天早上我会发布它,提醒我,如果我忘记了 – 2012-02-16 05:20:04

回答

2

请确保您遵循了他的问题中描述的所有步骤1-4 user700284。

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"); 
0

的URL已经无关行

se = new StringEntity(inputXML, HTTP.UTF_8); 

你确定是这行?

+0

aah.sorry.my bad.that不是line.Will编辑我的问题。 – user700284 2011-05-23 11:55:00

+0

你有没有试过把www。infront的网址,并试图在浏览器中打开该网站? – 2011-05-23 12:07:59

+0

是的。我也尝试添加www.Infact我在示例中使用的网址不是实际的网址。它仅用于说明目的。在浏览器中模拟器我可以打开该网站。 – user700284 2011-05-23 12:17:28

相关问题