【问题标题】:accessing asp.net web api http service from android从android访问asp.net web api http服务
【发布时间】:2012-09-09 22:40:57
【问题描述】:

我的开发盒上有一个在 Visual Studio 中运行的有效 ASP.NET Web API 服务。我可以轻松地从任一 I.E. 获得正确的结果。或 FireFox,输入:http://localhost:61420/api/products。但是当尝试使用我的 AVD 从我的 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; 
    } 
} 
} 

【问题讨论】:

    标签: android asp.net-web-api


    【解决方案1】:

    Visual Studio 开发 Web 服务器只接受来自本地主机的连接,而不接受来自网络或其他虚拟连接的连接。听起来 AVD 被视为远程主机。

    【讨论】:

      【解决方案2】:

      要从任何地方访问应用程序,请更改应使用的网络服务器。假设您使用的是 Windows 7 和 Visual Studio 2010,请确保您已安装 IIS 和所有必需的功能,并在项目设置中将本地 IIS 设置为网络服务器:

      可能需要以管理员身份启动 Visual Studio 以使用本地 IIS 运行它。

      【讨论】:

        【解决方案3】:

        使用您机器的实际 IP 地址,即http://192.168.0.xx

        只有您的本地机器可以访问 localhost,如果您在模拟器或设备上,它将通过 NAT 或您的 DHCP 从路由器获得不同的 IP。

        【讨论】:

        • 您的回答是有道理的,但是当我用本地 ip 替换 localhost 并逐步调试时,它不会从 InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 返回操作说明。如果我等待,我最终会得到套接字超时异常。认为我应该以此为问题重新发布。
        • 您可以从设备的浏览器访问该网址吗?即,是服务器问题吗?
        • 是的,这是服务器问题。我从来没有能够从浏览器或其他任何地方使用 192.168.xx 访问我的 devbox 上的网站。 AVD 中的浏览器的行为就像代码一样。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多