如何发现给定HTTP请求失败的原因?

时间:2013-03-09 06:15:44

标签: c#

我想发现导致链接不起作用的原因。链接应该显示特定的消息,如404或403,而不是不工作。如何发现HTTP状态导致给定请求失败?

if (!IsLinkWorking(link))
{
     //Here you can show the error. You don't specify how you want to show it.
     TextBox2.ForeColor = System.Drawing.Color.Green; 
     TextBox2.Text += string.Format("{0}\nNot working\n\n ", link);
}
else
{
     TextBox2.Text += string.Format("{0}\n working\n\n", link);
}

2 个答案:

答案 0 :(得分:2)

您需要使用HttpWebRequest。这将返回一个HttpWebResponse,它具有StatusCode属性 - see the documentation here

以下是一个例子:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
if (response.StatusCode != HttpStatusCode.OK) {
    TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}

答案 1 :(得分:1)

不工作链接的原因可能有很多,您可以使用正确的HTTP标头值尝试WebClientHttpWebRequest / HttpWebResponse来检查链接是否有效。

请注意,在403,404等错误的情况下,它会抛出您应该处理的异常,否则它将不会给您响应状态:

try{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    /* Set HTTP header values */
    request.Method = "MethodYouWantToUse"; // GET, POST etc.
    request.UserAgent = "SomeUserAgent";
    // Other header values here...

    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);

}
catch(WebException wex){
    if(wex.Response != null){
        HttpWebResponse response = wex.Response as HttpWebResponse;
            if (response.StatusCode != HttpStatusCode.OK) {
                TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
            }            
    }
}