HttpClient - 忽略404

时间:2014-01-07 11:51:25

标签: c# .net-4.5

快速提问。 HttpClient在404错误上抛出异常,但是从该请求返回的404页面在这个实例中对我的应用程序实际上是有用的。是否可以忽略404响应并将请求处理为200?

2 个答案:

答案 0 :(得分:1)

您可以使用异常

中的流来阅读404的内容
WebClient client = new WebClient();
try
{
    client.DownloadString(url);
}
catch (System.Net.WebException exception)
{
    string responseText;

    using (var reader = new System.IO.StreamReader(exception.Response.GetResponseStream()))
    {
        responseText = reader.ReadToEnd();
        throw new Exception(responseText);
    }
}

由其他人提供,但我无法找到我获得此信息的来源

答案 1 :(得分:0)

主机名解析失败与向已知主机请求不存在的文档的情况不同,必须单独处理。我怀疑你面临一个解决方案失败(因为它会抛出,而请求一个已知主机的不存在的资源不会抛出,但会给你一个很好的“NotFound”响应)。

以下代码段处理两种情况:

// urls[0] known host, unknown document
// urls[1] unknown host
var urls = new string[] { "http://www.example.com/abcdrandom.html", "http://www.abcdrandom.eu" };
using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = new HttpResponseMessage();
    foreach (var url in urls)
    {
        Console.WriteLine("Attempting to fetch " + url);
        try
        {
            response = await client.GetAsync(url);

            // If we get here, we have a response: we reached the host
            switch (response.StatusCode)
            {
                case System.Net.HttpStatusCode.OK:
                case System.Net.HttpStatusCode.NotFound: { /* handle 200 & 404 */ } break;
                default: { /* whatever */ } break;
            }
        }
        catch (HttpRequestException ex)
        {
            //kept to a bare minimum for shortness
            var inner = ex.InnerException as WebException;
            if (inner != null)
            {
                switch (inner.Status)
                {
                    case WebExceptionStatus.NameResolutionFailure: { /* host not found! */ } break;
                    default: { /* other */ } break;
                }
            }
        }
    }
}

WebExceptionStatus枚举包含要处理的代码的多种可能的失败(包括Unknown)。