2014-01-07 32 views
1

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

+2

我没有看到提到使用.NET 4.5的HttpClient的问题? –

+0

请注意我没有使用ASP.NET。这是一个WinForms应用程序。 –

+0

它看起来像你可能必须实现你自己的[httpmessagehandler](http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v = vs.110).aspx) – rene

回答

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)的代码来处理。

+0

404通常会引发异常,因此无法达到switch语句。不是100%确定是否在HttpClient中存在相同的行为 – MichaelD

+0

在404上没有引发异常,但是根本不能发送请求:即,您得到了名称解析失败(我怀疑是这种情况)的异常。我将更新代码 – Alex

+1

找不到服务器上的页面时引发异常。这是发生了什么事。 –

1

您可以使用流从异常别人的

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); 
    } 
} 

礼貌读取404的内容,但我无法找到在那里我得到这个信息源