HttpWebRequest.GetResponse()在第二次调用时挂起

Tim*_*tin 26 .net c# httpwebrequest

我正在尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)

症状似乎与这个问题这个问题非常相似,但在这两种情况下,给出的建议是处理我已经在做的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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:事实证明我犯了从我的问题中删除代码的主要罪过,我没有验证该代码与问题无关.我删除了以下行:

    if (m_contentLength > 0)
        httpWebRequest.ContentLength = m_contentLength;
Run Code Online (Sandbox Code Playgroud)

因为我认为永远不会为GET请求指定内容长度.事实证明我错了.删除此行可修复此问题.

我现在唯一的问题是为什么?我认为指定的内容长度是正确的,尽管它可能是一个.指定内容长度太短会阻止完整下载并导致连接保持打开状态?我原以为Close()和/或Dispose()应该杀死连接.

Dio*_*ogo 11

httpWebRequest.Abort(); // before you leave
Run Code Online (Sandbox Code Playgroud)

会解决!


Ada*_*Dev 8

确保每次都创建一个新的HttpWebRequest.引用来自GetResponse方法的MSDN参考 :

对GetResponse的多次调用返回相同的响应对象; 请求不会重新发布.

更新1: 好的.如果你尝试关闭webResponseStream怎么样 - 你现在不这样做,你只关闭webResponse(只是试图排除事情).我也会处理httpWebResponse(不仅仅是WebResponse)

更新2: 我可以建议的另一件事是看看我在做类似于你正在做的事情时看到的以下文章:
http://arnosoftwaredev.blogspot.com/2006/09/net -20-httpwebrequestkeepalive-and.html
http://www.devnewsgroups.net/dotnetframework/t10805-exception-with-httpwebrequest-getresponse.aspx

我做的唯一明显的事情是:
- set webrequest.KeepAlive = false
- 我没有配置中的连接管理内容(我不循环来发出一系列请求)