简体   繁体   中英

Getting an error when connecting to an API using HttpClient

This is a problem on the HttpClientWrapper ,tried connecting to the API endpoint from the device/emulator?

string result = _failedResult;
        try
        {
            using (var httpClient = new HttpClient())
            {
                //Set the headers
                httpClient.DefaultRequestHeaders.Accept.Clear();
                using (HttpResponseMessage responce = httpClient.GetAsync(uri).Result)
                {
                    if (responce.IsSuccessStatusCode)
                    {
                        result = responce.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        var reasonPhrase = responce.ReasonPhrase;
                        result = responce.Content.ReadAsStringAsync().Result;
                        var errormessage = string.Format("Error:{0} {1} for uri :{2} ", reasonPhrase, result, uri.ToString());
                    }
                }
            }
        }
        catch(Exception ex)
        {
            var t=ex.InnerException;
            result = ex.Message;
        }

        return result;

Expecting i need to get phonenumbers list as a JSON format from the server.

Instead I'm getting the following error:

System.Net.WebException: Error: ConnectFailure (Connection refused)-> System.Net.Sockets.SocketException: Connection refused

If you're using an Android Emulator then asking for the localhost web service won't work, because you're looking at the localhost of the emulator.

You can fix this as follows:

Android Emulator has a magic address http://10.0.2.2:your_port that points to 127.0.0.1:your_port on your host machine. Take a look here . Because it points to an IP and not localhost, you need to go into your project solution, in .vs folder -> config-> applicationhost.config and change this <binding protocol="http" bindingInformation="*:44388:localhost" /> into , where 44388 is your port. Restart IIS Express and you're good to go.

So use: " http://10.0.2.2:44388/api/Common/getPhonenumbers "

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