WebClient.DownloadString(URL)时,此URL返回一个404页面,我怎么能跳过这个? [英] WebClient.DownloadString(url) when this url returns a 404 page, how can i skip this?

查看:806
本文介绍了WebClient.DownloadString(URL)时,此URL返回一个404页面,我怎么能跳过这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WebClient.DownloadString(URL)来下载一个网页,当一个URL的404网页,它将停止并不再工作了。
我想,当我得到这个故障跳过这些页面。

I'm using WebClient.DownloadString(url) to download a web page, when a url a 404 web page it stops and doesn't work anymore. I want to skip these pages when I got this fault.

如果URL是404页,它不会开始下载。所以我不能解析undownloaded数据...

if the url is 404 page, it doesn't start to download. so i can't parse the undownloaded data...

推荐答案

您将不得不搭上404的异常和测试:

You will have to catch the Exception and test for a 404:

try
{
    string myString;
    using (WebClient wc = new WebClient())
        myString= wc.DownloadString("http://foo.com");

}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
    {
        var resp = (HttpWebResponse)ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
        {
            //the page was not found, continue with next in the for loop
            continue;
        }
    }
    //throw any other exception - this should not occur
    throw;
}

这篇关于WebClient.DownloadString(URL)时,此URL返回一个404页面,我怎么能跳过这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆