2

我想找出导致链接不起作用的原因。链接应该显示特定消息,而不是不起作用,例如 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);
}
4

2 回答 2

2

您需要使用 HttpWebRequest。这将返回一个具有 StatusCode 属性的 HttpWebResponse -请参阅此处的文档

这是一个例子:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
if (response.StatusCode != HttpStatusCode.OK) {
    TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
于 2013-03-09T06:37:52.770 回答
1

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

请注意,如果出现 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);
            }            
    }
}
于 2013-03-09T09:04:13.623 回答