快速的问题。 HttpClient在404错误中抛出异常,但从请求返回的404页实际上对我的应用程序有用。是否可以忽略404响应并将请求处理为200?HttpClient - 忽略404
1
A
回答
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
)的代码来处理。
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的内容,但我无法找到在那里我得到这个信息源
相关问题
- 1. HttpClient忽略AllowAutoRedirect指令
- 2. Angular 2,可以忽略Http.get 404
- 3. 如何配置Log4Net忽略404错误?
- 4. 404 Not Found with HttpClient
- 5. Automapper忽略属性忽略
- 6. IS忽略被忽略
- 7. svn:忽略不忽略xcuserdata
- 8. SVN忽略被忽略
- 9. bin - 忽略或不忽略
- 10. 如何使Apache Commons HttpClient 3.1忽略HTTPS证书无效?
- 11. PCL HttpClient响应忽略没有域名的Cookie
- 12. 如何在使用TLSv1.2的Apache HttpClient中忽略“localhost”?
- 13. 如何让HttpClient Json序列化程序忽略空值
- 14. 忽略饼干
- 15. 忽略
- 16. 忽略
- 17. 忽略
- 18. 忽略
- 19. android http请求忽略cookie
- 20. 为什么'svn忽略'不能忽略?
- 21. 忽略未被忽略的文件
- 22. vagrant忽略Vagrantfile安装点忽略
- 23. svn:忽略排除文件被忽略
- 24. mysqldump忽略表不会忽略视图
- 25. java webstart忽略System.getProperties()或Syste.setProperties()被忽略
- 26. 忽略SVN忽略...可能吗?
- 27. 摇篮忽略守护忽略标志
- 28. 为什么TestRestTemplate忽略404客户端错误?
- 29. application.log中奇怪的404错误,让YII忽略它们?
- 30. 如何告知应用程序见解忽略404响应
我没有看到提到使用.NET 4.5的HttpClient的问题? –
请注意我没有使用ASP.NET。这是一个WinForms应用程序。 –
它看起来像你可能必须实现你自己的[httpmessagehandler](http://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v = vs.110).aspx) – rene