HttpClient与HttpWebRequest获得更好的性能,安全性和更少的连接 [英] HttpClient vs HttpWebRequest for better performance, security and less connections

查看:339
本文介绍了HttpClient与HttpWebRequest获得更好的性能,安全性和更少的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现单个HttpClient可以被多个请求共享.如果共享,并且请求到达相同的目的地,则多个请求可以重用连接. WebRequest需要为每个请求重新创建连接.

I discovered that a single HttpClient could be shared by multiple requests. If shared, and the requests are to the same destination, multiple requests could reuse the connections. WebRequest needs to recreate the connection for each request.

我还在示例中查阅了有关使用HttpClient的其他方式的一些文档.

I also looked up some documentation on other ways to use HttpClient in examples.

下面的文章总结了经过NTLM身份验证的高速连接共享:

The following article summarizes the high-speed NTLM-authenticated connection sharing: HttpWebRequest.UnsafeAuthenticatedConnectionSharing  

我尝试过的可能的实现如下所示

Possible implementations that I tried out are shown below

A)

private WebRequestHandler GetWebRequestHandler()
{
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(ResourceUriCanBeAnyUri, "NTLM", CredentialCache.DefaultNetworkCredentials);
    WebRequestHandler handler = new WebRequestHandler
    {
        UnsafeAuthenticatedConnectionSharing = true,
        Credentials = credentialCache
    };

    return handler;
}

using (HttpClient client = new HttpClient(GetWebRequestHandler(), false))
{
}

B)

using (HttpClient client = new HttpClient)
{
}

C)

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("some uri string")

在帮助我理解应该采用哪种方法以实现最大性能,最小化连接并确保安全性不受影响方面,我将不胜感激.

I would appreciate any help in making me understand which approach I should take so as to achieve max performance, minimizing connections and making sure security is not impacted.

推荐答案

如果您将二者之一与async一起使用,则对于性能而言应该是不错的选择,因为它不会阻塞等待响应的资源,您将获得良好的吞吐量.

If you use either of them with async it should be good for the performance point of view as it will not block the resources waiting for the response and you will get good throughput.

与HttpWebRequest相比,HttpClient是首选的,因为它提供了开箱即用的异步方法,您不必担心编写begin/end方法.

HttpClient is preferred over HttpWebRequest due to async methods available out of the box and you would not have to worry about writing begin/end methods.

基本上,当您使用异步调用(使用任一类)时,它不会阻塞等待响应的资源,其他任何请求都将利用这些资源进行进一步的调用.

Basically when you use async call (using either of the class), it will not block the resources waiting for the response and any other request would utilise the resources to make further calls.

要记住的另一件事是,您不应在"using"块中使用HttpClient,以允许将相同的资源一次又一次地用于其他Web请求.

Another thing to keep in mind that you should not be using HttpClient in the 'using' block to allow reuse of same resources again and again for other web requests.

有关更多信息,请参见以下线程

See following thread for more information

是否必须处置HttpClient和HttpClientHandler?

这篇关于HttpClient与HttpWebRequest获得更好的性能,安全性和更少的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆