c# - 第二次调用 HttpWebRequest.GetResponse() 时挂起

标签 c# .net 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();
}

症状似乎与 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 请求指定内容长度。事实证明我错了。删除此行可解决问题。

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

最佳答案

httpWebRequest.Abort(); // before you leave

会解决的!

看看 resource .

关于c# - 第二次调用 HttpWebRequest.GetResponse() 时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2063937/

相关文章:

c# - 使用 C# 和 XAML 在 Metro 应用程序中自动滚动

c# - 对理解泛型接口(interface)的 C# 练习有一点帮助

c# - HttpWebRequest 对象的诊断转储

c# - 如何在不知道密码的情况下获取另一个用户的 WindowsIdentity?

c# - 转向 ASP.NET - VB 还是 C#?

c# - HttpWebRequest 丢失 cookie

c# - RTC授权总是失败

c# - 在 Entity Framework 中执行存储过程 - 没有定义键。 (代码第一)

c# - 作为代理或重定向器的负载平衡器

c# - ASP.NET 5 类库中的 Startup.cs