11

我有这个简单的函数来获取 HTML 页面并将其作为字符串返回;虽然有时我会收到 404。如何仅在请求成功时才返回 HTML 字符串,并返回类似于BadRequest404 或任何其他错误状态代码的内容?

public static string GetPageHTML(string link)
{
    using (WebClient client= new WebClient())
    {
        return client.DownloadString(link);
    }
}
4

1 回答 1

24

您可以捕获 WebException:

public static string GetPageHTML(string link)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString(link);
        }
    }
    catch (WebException ex)
    {
        var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
        return "An error occurred, status code: " + statusCode;
    }
}

当然,在调用代码中捕获此异常,甚至不尝试解析 html,而不是将 try/catch 放在函数本身中会更合适。

于 2013-03-08T08:15:16.203 回答