簡體   English   中英

400使用HttpWebRequest和HttpWebResponse檢查網站是否有效時出錯,為什么?

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

在此處使用以下代碼來確定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;
}

問題是,似乎使用以下URL返回false: https://www.paypal.com : http://www.paypal.com或什至http://www.paypal.com ,在日志中也給了我400錯誤。 這是為什么? 反正有解決這個問題的方法嗎?

您的代碼可用於其他站點。

貝寶不得響應HEAD請求。

返回的System.Net.WebException說“未處理”

解決此問題的最簡單方法就是使用GET。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM