如何解决"拒绝连接"来自.NET HttpClient,当URL从浏览器正常工作时

时间:2016-11-28 23:23:49

标签: rest xamarin

这是访问www.geonames.org网站的Xamarin应用程序。当我运行它时,它会生成一个System.Net.WebException"错误:ConnectFailure(连接被拒绝)"。但是,如果我使用此方法生成的url并将其粘贴到模拟器上的浏览器中,它可以正常工作并返回正确的JSON。

    public async Task GetWeatherAsync(double longitude, double latitude, string username)
    {
        var url = string.Format("http://api.geonames.org/findNearByWeatherJSON?lat={0}&lng={1}&username={2}", latitude, longitude, username);

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(url);

        try
        {
            var response = await client.GetAsync(client.BaseAddress);
            if (response.IsSuccessStatusCode)
            {
                var JsonResult = response.Content.ReadAsStringAsync().Result;
                var weather = JsonConvert.DeserializeObject<WeatherResult>(JsonResult);

                SetValues(weather);
            }
            else
            {
                Debug.WriteLine(response.RequestMessage);
            }
        }
        catch (HttpRequestException ex)
        {
            Debug.WriteLine(ex.Message);
        }
        catch (System.Net.WebException ex)
        {
            Debug.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:0)

解决方案是使用适当的代理设置添加HttpClientHandler。实例化IWebProxy的实例:

public class WebProxy : IWebProxy
{
    public ICredentials Credentials { get; set; }

    private readonly Uri _proxyUri;
    public WebProxy(string proxyString)
    {
        _proxyUri = new Uri(proxyString);
    }

    public WebProxy(Uri proxyUri)
    {
        _proxyUri = proxyUri;
    }

    public Uri GetProxy(Uri destination)
    {
        return _proxyUri;
    }

    public bool IsBypassed(Uri host)
    {
        return false;
    }
}

然后使用使用代理的处理程序实例化HttpClient

NetworkCredential proxyCreds = new NetworkCredential(
    ProxyConfig.Username, ProxyConfig.Password);

WebProxy proxy = new WebProxy(ProxyConfig.Url)
{
    Credentials = proxyCreds
};

HttpClientHandler handler = new HttpClientHandler
{
    PreAuthenticate = true,
    UseDefaultCredentials = false,
    Proxy = proxy
};

HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(url);