简体   繁体   English

400使用HttpWebRequest和HttpWebResponse检查网站是否有效时出错,为什么?

[英]400 Error when checking if website is valid with HttpWebRequest and HttpWebResponse Why?

Using the following code here to determine if a url is valid or not: 在此处使用以下代码来确定URL是否有效:

public bool UrlIsValid(string url)
{
    if(!url.ToLower().StartsWith("http://") && !url.ToLower().StartsWith("https://"))
    {
        url = "http://" + url;
    }

    try
    {
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
        request.Method = "HEAD"; //Get only the header information -- no need to download any content

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        int statusCode = (int)response.StatusCode;
        if (statusCode >= 100 && statusCode < 400) //Good requests
        {
            return true;
        }
        else if (statusCode >= 500 && statusCode <= 510) //Server Errors
        {
            log.Warn(String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
            return false;
        }
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
        {
            log.Warn(String.Format("400 Error logged: {0}", url));
            return false;
        }
        else
        {
            log.Warn(String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url), ex);
        }
    }
    catch (Exception ex)
    {
        log.Error(String.Format("Could not test url {0}.", url), ex);
    }
    return false;
}

Problem is it seems to return false with the following url: https://www.paypal.com or even with http://www.paypal.com giving me a 400 Error in the logs. 问题是,似乎使用以下URL返回false: https://www.paypal.com : http://www.paypal.com或什至http://www.paypal.com ,在日志中也给了我400错误。 Why is that? 这是为什么? Is there anyway to get around this? 反正有解决这个问题的方法吗?

Your code is fine for other sites. 您的代码可用于其他站点。

PayPal must not respond to HEAD requests. 贝宝不得响应HEAD请求。

The System.Net.WebException returned says 'Unhandled' 返回的System.Net.WebException说“未处理”

The easiest way around this is just to use a GET. 解决此问题的最简单方法就是使用GET。

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

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