2012-09-09 153 views
1

我有一個工作的ASP.NET Web API服務在我的開發箱上的Visual Studio中運行。我可以很容易地從I.E.獲得正確的結果。或輸入:http://localhost:61420/api/products FireFox。但是當試圖從我的Android項目中使用我的AVD讀取它時,我得到一個異常拋出:訪問asp.net web api http服務從android

localhost/127.0.0.1:61420 - 連接被拒絕。

我知道我的Android Java代碼有效,因爲我可以訪問在我的網站上運行的WCF RESTFul服務(該URL目前已被註釋掉)。我的Android代碼粘貼在下面。

那麼,爲什麼我在從Eclipse項目訪問時收到錯誤信息,但是從瀏覽器訪問時卻沒有收到錯誤信息? 感謝

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    HttpURLConnection urlConnection = null; 

    try 
    { 
     //URL url = new URL("http://www.deanblakely.com/myRESTService/SayHello"); 
     URL url = new URL("http://localhost:61420/api/products"); 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());  
     String myString = readStream(in); 
     String otherString = myString; 
     otherString = otherString + " "; 
    } 
    catch (MalformedURLException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    {  
     urlConnection.disconnect(); 
    } 
} 

private String readStream(InputStream is) 
{ 
    try 
    { 
     ByteArrayOutputStream bo = new ByteArrayOutputStream(); 
     int i = is.read(); 

     while(i != -1) 
     { 
      bo.write(i); 
      i = is.read(); 
     } 

     return bo.toString(); 
    } 
    catch (IOException e) 
    { 
     return "" + e; 
    } 
} 
} 

回答

0

使用你的機器,即實際的IP地址,http://192.168.0.xx

只有本地計算機可以訪問本地主機,如果你是在模擬器或設備,其將不得不通過不同的IP無論是NAT還是來自路由器的DHCP。

+0

你的答案是有道理的,但是當我用本地ip替換本地主機並且通過調試時它不會從InputStream返回= new BufferedInputStream(urlConnection.getInputStream());指令。如果我等待,我最終會得到套接字超時異常。認爲我應該重新發布這個問題。 –

+0

您可以從設備的瀏覽器訪問該網址嗎?即它是一個服務器問題? – tsmith

+0

是的,這是一個服務器問題。我從來沒有能夠從瀏覽器或其他地方使用192.168.x.x訪問我的devbox上的網站。 AVD中的瀏覽器就像代碼一樣。 –

2

Visual Studio開發Web服務器將只接受來自本地主機的連接,而不是通過網絡或其他虛擬連接。聽起來像AVD被視爲遠程主機。

1

要從任何地方訪問應用程序,請更改應使用的網絡服務器。假設你使用的是Windows 7和Visual Studio 2010中,請確保您有IIS並安裝所有需要的功能和設置本地IIS作爲您的項目設置Web服務器:

project settings

這可能是需要啓動Visual Studio作爲管理員使用本地IIS運行它。