我有一个工作的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中的浏览器就像代码一样。 –