c# - 如何跳过 HttpWebResponse 404

标签 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 时跳过该 url 并继续到下一个 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;
                }
            }

最佳答案

捕获错误并检查其状态。如果是 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;
        }
    }

}

关于c# - 如何跳过 HttpWebResponse 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915897/

相关文章:

github - 如何在GitHub Pages上设置自定义404页面?

php - 如何检测 php curl 中的 URL Not Found 错误?

c# - 大写字母的 URL 编码

c# - 如何在 visual studio 2015 中使用 roslyn c# 编译器?

c# - 将 ListView 绑定(bind)到具有对象类型的 List<T> 或 List<InterfaceOfT>

windows - TLS1.2 Powershell HttpWebClient 支持

spring-mvc - org.springframework.web.servlet.PageNotFound noHandlerFound;警告 : No mapping found for HTTP request with URI in DispatcherServlet

c# - SQL 数据库中的多个条目而不是一个条目。 (可能是由于 session ?)

javascript - 从数据数组发送恒定大小的批量请求 - React、Axios

c# - 通过 SSL 使用 HttpWebRequest 发送请求时出现错误 502(错误的网关)