繁体   English   中英

使用HttpClient连接到API时出现错误

[英]Getting an error when connecting to an API using HttpClient

这是HttpClientWrapper上的问题,试图从设备/仿真器连接到API端点吗?

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;

期望我需要从服务器获取电话号码列表作为JSON格式。

相反,我收到以下错误:

System.Net.WebException:错误:ConnectFailure(连接被拒绝)-> System.Net.Sockets.SocketException:连接被拒绝

如果您使用的是Android Emulator那么请求localhost Web服务将不起作用,因为您正在查看模拟器的localhost

您可以按以下方式解决此问题:

Android Emulator的魔幻地址为http://10.0.2.2:your_port ,它指向主机上的127.0.0.1:your_port 在这里看看。 因为它指向IP,而不是localhost,所以您需要进入项目解决方案,位于.vs文件夹-> config-> applicationhost.config中,并更改此<binding protocol="http" bindingInformation="*:44388:localhost" />进入,其中44388是您的端口。 重新启动IIS Express,一切顺利。

因此,请使用:“ http://10.0.2.2:44388/api/Common/getPhonenumbers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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