2012-09-09 151 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运行它。