简体   繁体   中英

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. It works fine for small JSON, but when I request a large one - something goes wrong. By large one I mean something that takes 1-2 minutes to appear in a browser (google chrome, including server side generation time). It's actually 412KB of text. When I try to ask for the same JSON with the method above I get a web exception (timeout). I changed the timeout to 10 minutes (at least 5 times longer than chrome). Still the same.

Any ideas?

EDIT

This seems to have something to do with MS technologies. On IE this JSON also won't load.

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()) {...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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