簡體   English   中英

使用 HttpWebRequest 減慢第一個 HTTP 請求

[英]Slow first HTTP request with HttpWebRequest

所以我試圖在我的 Revit(BIM 軟件)的 C# 插件中使用 HttpWebRequest,向我的 API 發送請求。 但是每次我嘗試這樣做時,它所花費的時間都比 Chrome/Firefox/Postman 中的請求要長。

如果我通過 Postman 發送我的請求,大約需要 1 到 1.5 秒。 但是如果我在我的應用程序中發送它,大約需要 21 到 21.5 秒。 所以看起來 HttpWebrequest 創建了某種超時,但我似乎無法弄清楚為什么會這樣。

我的代碼:

static public string Get(string baseURI, Dictionary<string, string> requestParameters)
    {
        ServicePointManager.UseNagleAlgorithm = false;
        ServicePointManager.DefaultConnectionLimit = 15;
        string requestURI = baseURI;

        if (requestURI.Length != 0)
        {
            foreach (KeyValuePair<string, string> parameter in requestParameters)
            {
                if (requestURI[requestURI.Length - 1] != '?')
                {
                    requestURI = requestURI + '&';

                }
                requestURI = requestURI + parameter.Key + "=" + parameter.Value;
            }
        }

        HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;

        request.Method = "GET";
        string results = string.Empty;
        request.Proxy = null;
        request.KeepAlive = false;

        HttpWebResponse response;
        using (response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream  
            StreamReader reader = new StreamReader(response.GetResponseStream());
            results = reader.ReadToEnd();
            reader.Close();
            response.Close();
        }

        return results;
    }

我嘗試了以下方法:

  • 使用 RestSharp

  • 使用 HttpWebRequest

  • 發送兩個請求(兩個不同的請求相同),其中第二個請求只需要 1.5 秒,這是應該的。

  • 我試過 request.Proxy = null; /ServicePointManager.UseNagleAlgorithm = false; / request.KeepAlive / ServicePointManager.DefaultConnectionLimit = 15;

我想不出別的了,調試器也沒有給我任何有用的信息,說明它在這 20 秒內做了什么。

我在 Autohotkey 中處理這個問題。 但基本上使用相同的 ComObjCreate("WinHttp.WinHttpRequest.5.1")。

我發現在 Windows 上的網絡適配器設置中關閉 IPV6 協議解決了這個問題。

所以它真的可能是服務器端與 IPV6 的兼容性。 20 秒后回退到 IPV4 並且任何下一個請求運行良好。 只需嘗試轉動 IPV6。

我將深入研究如何強制 WinHttpRequest 使用 IPV4。

一些資源:WINHTTP_OPTION_IPV6_FAST_FALLBACK

https://docs.microsoft.com/en-us/windows/win32/winhttp/option-flags

https://docs.microsoft.com/en-us/windows/win32/winhttp/iwinhttprequest-option

https://github.com/wine-mirror/wine/blob/master/include/winhttp.h

https://tools.ietf.org/html/rfc6555

不幸的是,這個參數與 WinHttpRequest.5.1 不兼容,因為它是 WinHttp 的參數。

解決方法是在注冊表中禁用 IPV6(需要重新啟動),或者更好,Microsoft 建議使用 prefixpolicy。

https://kb.firedaemon.com/support/solutions/articles/4000160803-prioritising-ipv4-over-ipv6-on-windows-10

首選 IPV4 而不是 IPV6

commandline: 
netsh interface ipv6 set prefixpolicy ::ffff:0:0/96 46 4

比 IPV4 更喜歡 IPV6

commandline: 
netsh interface ipv6 set prefixpolicy ::ffff:0:0/96 35 4

以管理員身份運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM