C# 【Http请求返回】性能优化500毫秒到 60 毫秒

偶然发现 C# 的 HttpRequest 要比 Chrome 请求同一Url 慢好多。C# HttpRequest 要500毫秒 而Chrome 只需要 39ms。

作为有责任感的 码农。这个 必须优化。。

后来 整理 各种方法做了优化 

HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;

request.ServicePoint.UseNagleAlgorithm = false;
request.ServicePoint.ConnectionLimit = 65500;
request.AllowWriteStreamBuffering = false; 
request.Proxy = null;
response.Close();
request.Abort();

打开 KeepAlive 属性,这个可以打开一个tcp连接并在 一段时内重用tcp连接,从而加快http 请求。(默认是打开的)(我在开启keepalive 时出现 服务器关闭连接的错误,在请求完成后 加response.Close();request.Abort(); 后 错误消失)
Expect100Continue  的作用

发送一个请求, 包含一个Expect:100-continue, 询问Server使用愿意接受数据
接收到Server返回的100-continue应答以后, 才把数据POST给Server
所以关闭它可以加快http 请求。
还有 ConnectionLimit 默认是2 ,就是说 系统 只能 并发 2个http 请求,所以 这个属性可以以适当增大。


Proxy 属性在 .Net 4.0 时应该在 config 文件中增加:

<system.net>
<defaultProxy
enabled="false"
useDefaultCredentials="false" >
<proxy/>
<bypasslist/>
<module/>
</defaultProxy>
</system.net>
</configuration>

其他版本.NET 可以设置为null。
原因:NET4.0或3.5中的默认代理是开启的,而我并没有设置!故只有等待超时后才会绕过代理,这就阻塞了.其他的可以自己百度。到这了 http 的响应速度由原来 的500ms 减小的60ms,但还是 比不上Chrome。希望在以后有更好的办法加快。

 

转载:https://www.cnblogs.com/hnsongbiao/p/9815808.html

 

posted @ 2019-11-29 09:16  沙耶  阅读(1994)  评论(0编辑  收藏  举报