偶然發現 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