2013-03-14 249 views
1

我的方法是这样的:的WebRequest极其缓慢

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,但是当我请求一个很大的时候 - 出现问题。我的意思是,大概需要1-2分钟才能出现在浏览器中(谷歌浏览器,包括服务器端生成时间)。它实际上是412KB的文本。当我尝试用上面的方法请求相同的JSON时,我得到一个web异常(超时)。我将超时时间改为10分钟(至少比chrome长5倍)。还是一样。

任何想法?

编辑

这似乎有些事情要与MS技术。在IE中,这个JSON也不会加载。

回答

0

确保您关闭了您的请求。否则,一旦你达到允许的连接数量的最大值(对于我来说,只有一次),你必须等待较早的连接超时。这是最好使用

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