http客户端,不会抛出错误
问题描述:
我正在寻找C#HTTP客户端,它不会抛出,当它得到一个HTTP错误(404例如)。 这不仅仅是一个风格问题;它完全有效的非2xx答复有一个身体,但我不能得到它,如果HTTP堆栈抛出时做一个GetResponse()http客户端,不会抛出错误
答
所有返回Task<HttpResponseMessage>
的System.Net.Http.HTTPClient
方法不是扔在任何HttpStatusCode上。他们只会抛出超时,取消或无法连接到网关。
答
实现一个包装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.
}
}
答
如果您使用的是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的几乎所有方法都是线程安全的,我建议你真正创建一个静态的客户端代码中的其他地方使用,你是不是浪费内存的方式,如果你赚了很多的请求通过不断创造摧毁客户只有一个请求时埃可以做成千上万。
你可以得到的回应 http://*.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba HTTP ://*.com/questions/18403846/httpwebrequest-accept-500-internal-server-error – CaldasGSM
@ CaldasGSM - 啊哈 - 我没有意识到 - ty – pm100