简体   繁体   English

WebRequest非常慢

[英]WebRequest extremely slow

My method looks like this: 我的方法如下所示:

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;
}

The server sends JSON in response. 服务器发送JSON作为响应。 It works fine for small JSON, but when I request a large one - something goes wrong. 它适用于小型JSON,但是当我请求大型JSON时,出现了问题。 By large one I mean something that takes 1-2 minutes to appear in a browser (google chrome, including server side generation time). 总的来说,我的意思是某种东西需要1-2分钟才能出现在浏览器中(谷歌浏览器,包括服务器端生成时间)。 It's actually 412KB of text. 实际上是412KB的文字。 When I try to ask for the same JSON with the method above I get a web exception (timeout). 当我尝试使用上述方法请求相同的JSON时,出现网络异常(超时)。 I changed the timeout to 10 minutes (at least 5 times longer than chrome). 我将超时时间更改为10分钟(至少是Chrome的5倍)。 Still the same. 还是一样。

Any ideas? 有任何想法吗?

EDIT 编辑

This seems to have something to do with MS technologies. 这似乎与MS技术有关。 On IE this JSON also won't load. 在IE上,此JSON也不会加载。

Make sure you close your request. 确保关闭请求。 Otherwise, once you hit the maximum number of allowed connections (as low as four, for me, on one occasion), you have to wait for the earlier ones to time out. 否则,一旦达到允许的最大连接数(对我而言,一次只有四个),就必须等待较早的连接超时。 This is best done using 最好使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM