我有一個工作的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;
}
}
}
你的答案是有道理的,但是當我用本地ip替換本地主機並且通過調試時它不會從InputStream返回= new BufferedInputStream(urlConnection.getInputStream());指令。如果我等待,我最終會得到套接字超時異常。認爲我應該重新發布這個問題。 –
您可以從設備的瀏覽器訪問該網址嗎?即它是一個服務器問題? – tsmith
是的,這是一個服務器問題。我從來沒有能夠從瀏覽器或其他地方使用192.168.x.x訪問我的devbox上的網站。 AVD中的瀏覽器就像代碼一樣。 –