本文介绍了HttpClient无法访问简单的网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

internal static  void ValidateUrl(string url)
{
    Uri validUri;
    if(Uri.TryCreate(url,UriKind.Absolute,out validUri))
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {                    
                HttpResponseMessage response = client.Get(url);
                response.EnsureStatusIsSuccessful();
            }
            catch (Exception ex)
            {
                  //exception handler goes here 
            }
        }
    }
}

运行此代码时会生成此结果。

This code when i run it produces this result.

ProxyAuthenticationRequired (407) is not one of the following: 
OK (200), Created (201), Accepted (202), NonAuthoritativeInformation
(203), NoContent (204), ResetContent (205), PartialContent (206).

我想做的就是让这段代码验证一个给定的网站是否正常运行。
任何想法?

All i want to do is make this code validate whether a given website is up and running. Any ideas?

推荐答案

您正在调用EnsureStatusIsSuccessful(),它正确地抱怨请求未成功,因为有一个您和要求身份验证的主机之间的代理服务器。

You are invoking EnsureStatusIsSuccessful() which rightfully complains that the request was not successful because there's a proxy server between you and the host which requires authentication.

如果您使用的是框架4.5,我在下面添加了一个略微增强的版本。

If you are on framework 4.5, I've included a slightly enhanced version below.

internal static async Task<bool> ValidateUrl(string url)
{
  Uri validUri;
  if(Uri.TryCreate(url,UriKind.Absolute,out validUri))
  {
    var client = new HttpClient();

    var response = await client.GetAsync(validUri, HttpCompletionOption.ResponseHeadersRead);
    return response.IsSuccessStatusCode;
  }

  return false;
 }

这篇关于HttpClient无法访问简单的网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 18:43