簡體   English   中英

WebRequest非常慢

[英]WebRequest extremely slow

我的方法如下所示:

public string Request(string action, NameValueCollection parameters, uint? timeoutInSeconds = null)
{
    parameters = parameters ?? new NameValueCollection();
    ProvideCredentialsFor(ref parameters);

    var data = parameters.ToUrlParams(); // my extension method converts the collection to a string, works well

    byte[] dataStream = Encoding.UTF8.GetBytes(data);
    string request = ServiceUrl + action;
    var webRequest = (HttpWebRequest)WebRequest.Create(request);
    webRequest.AllowAutoRedirect = false;
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = dataStream.Length;
    webRequest.Timeout = (int)(timeoutInSeconds == null ? DefaultTimeoutMs : timeoutInSeconds * 1000);
    webRequest.Proxy = null; // should make it faster...

    using (var newStream = webRequest.GetRequestStream())
    {
        newStream.Write(dataStream, 0, dataStream.Length);
    }
    var webResponse = (HttpWebResponse)webRequest.GetResponse();

    string uri = webResponse.Headers["Location"];

    string result;
    using (var sr = new StreamReader(webResponse.GetResponseStream()))
    {
        result = sr.ReadToEnd();
    }


    return result;
}

服務器發送JSON作為響應。 它適用於小型JSON,但是當我請求大型JSON時,出現了問題。 總的來說,我的意思是某種東西需要1-2分鍾才能出現在瀏覽器中(谷歌瀏覽器,包括服務器端生成時間)。 實際上是412KB的文字。 當我嘗試使用上述方法請求相同的JSON時,出現網絡異常(超時)。 我將超時時間更改為10分鍾(至少是Chrome的5倍)。 還是一樣。

有任何想法嗎?

編輯

這似乎與MS技術有關。 在IE上,此JSON也不會加載。

確保關閉請求。 否則,一旦達到允許的最大連接數(對我而言,一次只有四個),就必須等待較早的連接超時。 最好使用

using (var response = webRequest.GetResponse()) {...

暫無
暫無

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

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