HttpClient failing in accessing simple website

▼魔方 西西 提交于 2019-12-13 05:15:25

问题


Here is my code

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?


回答1:


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.

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



回答2:


This basically means exactly what it says: That you are trying to access the service via a proxy that you are not authenticated to use.

I guess that means your server was reached from the Web Service, but that it was not permitted to access the URL it tried to reach, since it tried to access it through a proxy it was not authenticated for.




回答3:


It's what EnsureStatusIsSuccessful() does, it throws an exception if status code (returned from web server) is not one of that ones.

What you can do, to simply check without throwing an exception is to use IsSuccessStatusCode property. Like this:

HttpResponseMessage response = client.Get(url);
bool isValidAndAccessible = response.IsSuccessStatusCode;

Please note that it simply checks if StatusCode is within the success range.

In your case status code (407) means that you're accessing that web site through a proxy that requires authentication then request failed. You can do following:

  • Provide settings for Proxy (in case defaults one doesn't work) with WebProxy class.
  • Do not download page but just try to ping web server. You won't know if it's a web page or not but you'll be sure it's accessible and it's a valid URL. If applicable or not depends on context but it may be useful if HTTP requests fails.

Example from MSDN using WebProxy with WebRequest (base class for HttpWebRequest):

var request = WebRequest.Create("http://www.contoso.com");
request.Proxy = new WebProxy("http://proxyserver:80/",true);

var response = (HttpWebResponse)request.GetResponse();
int statusCode = (int)response.StatusCode;
bool isValidAndAccessible = statusCode >= 200 && statusCode <= 299;


来源:https://stackoverflow.com/questions/19380352/httpclient-failing-in-accessing-simple-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!