2012-03-22 26 views
1

我正在解析一個xml文件。
其中一個方法是如下:如何通過localhost鏈接進行替換? Android

public static String getXML(){ 
     String line = null; 

     try { 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost("http://p-xr.com/xml/"); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      line = EntityUtils.toString(httpEntity); 

     } catch (UnsupportedEncodingException e) { 
      line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
     } catch (MalformedURLException e) { 
      line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
     } catch (IOException e) { 
      line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
     } 

     return line; 

} 

在這裏,我想通過

HttpPost httpPost = new HttpPost("http://127.0.0.1/myfile.xml"); 

更換

HttpPost httpPost = new HttpPost("http://p-xr.com/xml/"); 

,我可以在我的瀏覽器瀏覽http://127.0.0.1/myfile.xml。 但是,當我把這個地址寫到上面的代碼時,它可以工作。 爲什麼? 我的項目需要http方法來訪問xml文件。

回答

1

在這種情況下使用10.0.2.2,查看Emulator Networking

+0

它工作正常。 但是結果顯示的時間很短,強制關閉錯誤出現。 但是,當我用'http:// p-xr.com/xml /'替換'http:// 10.0.2.2/myfile.xml'時,沒有任何強制關閉出現。 Thanx! – captaindroid 2012-03-22 08:33:30

+0

@captainpirate,很高興聽到它的幫助:) – yorkw 2012-03-22 10:17:26

2

在模擬器中,localhost是模擬器本身,而不是你的系統,它運行模擬器。所以它不會工作。

改爲使用10.0.2.2。

1

如果你想使用Android做到這一點設備:

通過在Mac或Linux上使用ifconfig或在Windows上使用ipconfig,可以找出計算機的IP地址。

然後,您可以用該IP地址替換p-xr.com/127.0.0.1。

您需要確保您的計算機上沒有設置防火牆,如果需要,您必須允許訪問您的Android設備才能聯繫您的本地HTTP服務器。

+0

感謝所有人的答覆。它工作gr8,我有這個頭痛2天。 – captaindroid 2012-03-22 05:46:39