【发布时间】:2010-01-14 12:17:52
【问题描述】:
我正在尝试使用 HttpWebRequest 通过 HTTP 获取一系列文件。第一个请求通过正常,但第二次通过相同的代码 GetResponse() 挂起并超时。 WireShark 显示没有为第二个请求发送 HTTP 流量,因此看起来这是一个 API 问题。
经过一番调查,我发现它与指定内容长度有关:如果我忽略它,那么代码可以正常工作。
我的代码是:
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,我已经在这样做了。
编辑响应 Gregory,这里是 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 请求指定内容长度。事实证明我错了。删除此行可以解决问题。
我现在唯一的问题是为什么?我认为指定的内容长度是正确的,尽管它可能会偏离 1。指定过短的内容长度会阻止完全下载并导致连接保持打开状态吗?我本来希望 Close() 和/或 Dispose() 无论如何都应该终止连接。
【问题讨论】:
-
你能发布 ConfigureRequest() 吗?
-
另外,回复:stackoverflow.com/questions/1386628/… 您是否尝试过将 JSkeet 提到的值配置为更高的值,即 4 或 8,看看这是否会改变什么?
-
@Tim Martin:你删除了哪一行? if 子句和 ContentLength 的设置?所以你根本不设置内容长度?我尝试删除 ContentLenght 的设置,但我仍然遇到同样的问题。
-
我遇到了类似的问题。这解决了我的问题:stackoverflow.com/questions/15181050/…
标签: c# .net httpwebrequest