简体   繁体   中英

accessing asp.net web api http service from android

I have a working ASP.NET Web API service running in Visual Studio on my dev box. I can easily get the proper results from either IE or FireFox by entering: http://localhost:61420/api/products . But when trying to read it from my Android Project using my AVD I get an exception thrown saying:

localhost/127.0.0.1:61420 - Connection refused.

I know my Android Java code works because I can access the WCF RESTFul service running on my Website (the URLthat's currently commented out). My Android code is pasted below.

So, why am I getting the error when accessing from my Eclipse project but not when accessing it from a browser? Thanks

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; 
    } 
} 
} 

Visual Studio development web server will only accept connections from the local host and not over the network or other virtual connection. Sounds like AVD is seen as a remote host.

To access the app from anywhere, change the webserver that should be used. Assuming you're using Windows 7 and Visual Studio 2010, make sure you have IIS and all required features installed and set the local IIS as the webserver in your project settings:

项目设置

It could be necessary to start Visual Studio as a Administrator to run it with local IIS.

Use the actual IP address of your machine ie, http://192.168.0.xx

Only your local machine can access localhost, and if you are on the emulator or a device, it will have a different IP through either NAT or your DHCP from the router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM