【发布时间】:2013-12-09 18:51:17
【问题描述】:
我正在寻找在收到 HTTP 错误(例如 404)时不会抛出的 c# HTTP 客户端。 这不仅仅是风格问题。它对于非 2xx 回复具有正文完全有效,但如果 HTTP 堆栈在执行 GetResponse() 时抛出,我无法理解它
【问题讨论】:
-
@CaldasGSM - 啊哈 - 我没有意识到 - ty
标签: c# dotnet-httpclient
我正在寻找在收到 HTTP 错误(例如 404)时不会抛出的 c# HTTP 客户端。 这不仅仅是风格问题。它对于非 2xx 回复具有正文完全有效,但如果 HTTP 堆栈在执行 GetResponse() 时抛出,我无法理解它
【问题讨论】:
标签: c# dotnet-httpclient
所有返回Task<HttpResponseMessage> 的System.Net.Http.HTTPClient 方法不会 抛出任何HttpStatusCode。它们只会引发超时、取消或无法连接到网关。
【讨论】:
如果你在 System.Net.Http 中使用 HttpClient,你可以这样做:
using (var client = new HttpClient())
using (var response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStreamAsync();
// You can do whatever you want with the resulting stream, or you can ReadAsStringAsync, or just remove "Async" to use the blocking methods.
}
else
{
var statusCode = response.StatusCode;
// You can do some stuff with the status code to decide what to do.
}
}
由于 HttpClient 上的几乎所有方法都是线程安全的,我建议您实际上创建一个静态客户端以在代码的其他地方使用,这样如果您通过不断创建销毁客户端来发出大量请求,就不会浪费内存当他们可以赚到数千时,只需一个请求。
【讨论】:
如何实现一个包装 HttpClient 的类?
让它实现委托给客户端对象的所需方法,并尝试/捕获这些委托方法中的异常。
class MyClient
{
HttpClient client;
[...]
public String WrappedMethodA()
{
try {
return client.MethodA();
} catch(Exception x) {
return ""; // or do some other stuff.
}
}
}
实现您自己的客户端后,您将摆脱这些异常。
如果您需要一个 HttpClient 实例,请从 HttpClient 继承并覆盖它的方法,如下所示:
public String WrappedMethodA()
{
try {
return base.MethodA(); // using 'base' as the client object.
} catch(Exception x) {
return ""; // or do some other stuff.
}
}
【讨论】: