我试图通过HTTP获取一系列文件,使用HttpWebRequest。第一个请求通过罚款,但第二次通过相同的代码GetResponse()挂起并超时。 WireShark显示没有为第二个请求发送HTTP流量,所以看起来这是一个API问题。HttpWebRequest.GetResponse()第二次挂起时调用
经过一番调查后,我发现它与指定内容长度有关:如果我不写,代码就可以正常工作。
我的代码是:
HttpWebRequest httpWebRequest = ConfigureRequest();
using (WebResponse webResponse = httpWebRequest.GetResponse())
// On the second iteration we never get beyond this line
{
HttpWebResponse httpWebResponse = webResponse as HttpWebResponse;
using (Stream webResponseStream = httpWebResponse.GetResponseStream())
{
if (webResponseStream != null)
{
// Read the stream
}
}
statusCode = httpWebResponse.StatusCode;
httpWebResponse.Close();
}
的症状似乎非常相似,this question和this question,但在这两种情况下,给出的建议是处置WebResponse的,这我已经在做的。
编辑针对格雷戈里,这里是ConfigureRequest():
private HttpWebRequest ConfigureRequest()
{
string sUrl = CreateURL(bucket, key);
HttpWebRequest httpWebRequest = WebRequest.Create(sUrl) as HttpWebRequest;
httpWebRequest.AllowWriteStreamBuffering = false;
httpWebRequest.AllowAutoRedirect = true;
httpWebRequest.UserAgent = this.m_sUserAgent;
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = this.m_iTimeout;
// *** NB: This line was left out of my original posting, and turned out to be
// crucial
if (m_contentLength > 0)
httpWebRequest.ContentLength = m_contentLength;
httpWebRequest.Headers.Add(StaticValues.Amazon_AlternativeDateHeader, timestamp);
httpWebRequest.Headers.Add(StaticValues.HttpRequestHeader_Authorization, StaticValues.Amazon_AWS + " " + aWSAccessKeyId + ":" + signature);
return httpWebRequest;
}
编辑:原来我承诺从我的问题删除代码的大罪,我还没有证实是与问题无关。我删除了以下行:
if (m_contentLength > 0)
httpWebRequest.ContentLength = m_contentLength;
因为我认为内容长度永远不会被指定为GET请求。原来我错了。删除这条线可以解决问题。
我现在唯一的问题是为什么?我认为指定的内容长度是正确的,虽然它可能是关闭的。指定内容长度太短会阻止完全下载并导致连接保持开放状态?我会期望Close()和/或Dispose()应该终止连接。
您可以发布ConfigureRequest()? – Gregory 2010-01-14 13:03:41
此外,重试:http://stackoverflow.com/questions/1386628/webrequest-getresponse-locks-up你试过配置JSkeet的值提到更高的东西,即4或8,看看这是否会改变什么? – Gregory 2010-01-14 13:05:47
@Tim Martin:你删除了哪一行? if-clause和ContentLength的设置?所以你根本不设置内容长度?我尝试删除ContentLenght的设置,但我仍然有同样的问题。 – Ted 2011-12-04 19:11:30