如何跳过HttpWebResponse 404

时间:2012-12-17 14:20:53

标签: c# httpwebrequest http-status-code-404 httpwebresponse system.net.httpwebrequest

嗨,我有一个可以查看某些页面的程序

for (int i=1; i < 1000; i++)
{
  string id = i.ToString();
  string url_source = get_url_source("http://mysite.com/"+id);
}

和方法

    public static string get_url_source(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
        return sr.ReadToEnd();
    }

我应该如何更改我的方法,以便主程序只会跳过该网址,并在发生404-notfound时继续使用下一个ID?

我把循环改成了

try
            {
                string url_source = get_url_source(url);
            }
            catch(WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    ConsoleBox.Text += i + ": " + WebExceptionStatus.ProtocolError.ToString() + "\r\n";
                    continue;
                }
                else
                {
                    throw;
                }
            }

4 个答案:

答案 0 :(得分:3)

捕获错误并检查其状态。如果是404 - 继续循环,否则重新抛出它。

for (int i=1; i < 1000; i++)
{
    string id = i.ToString();
    try
    {
         string url_source = get_url_source("http://mysite.com/"+id);
    }
    catch(WebException ex)
    {
        HttpWebResponse webResponse = (HttpWebResponse)ex.Response;          
        if (webResponse.StatusCode == HttpStatusCode.NotFound)
        {
            continue;
        }
        else
        {
            throw;
        }
    }

}

答案 1 :(得分:2)

你需要捕获当你执行GetResponseStream时抛出的WebException

try
{
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
    return sr.ReadToEnd();
}
catch (WebException webEx)
{
    //If you want only 404, some logic here
    //if (((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.NotFound)
    //{
    //}
    //else
    //{
    //      throw;
    //}
    //webEx.Status;
}

答案 2 :(得分:0)

尝试:            if(response.StatusCode == HttpStatusCode.OK)

答案 3 :(得分:0)

使用try / catch,将WebException作为异常类型。你可以测试一下状态:

 ex.Response.StatusCode==HttpStatusCode.NotFound