2011-05-23 40 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

相關問題