发送POST请求:System.Net.WebException

时间:2009-03-09 09:17:04

标签: c# .net post https httpwebrequest

这不是我第一次使用此方法发送POST请求,而且我从来没有遇到任何问题:

    public static Stream SendPostRequest(Uri uri, byte[] postData)
    {
        var request = WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.Length;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(postData, 0, postData.Length);
        requestStream.Close();
        return request.GetResponse().GetResponseStream();
    }

on request.GetRequestStream()我收到一个System.Net.WebException:底层连接已关闭:发送时发生意外错误。
更有趣的是,它在某些机器上运行得非常好,但在我的机器(Windows 7 Beta)和生产服务器(Windows Server 2008)上不起作用。更多信息:

Works - Windows Xp - .NET 2.0
Works - Windows Xp - .NET 3.5
Works - Windows Server 2003 - .NET 3.0
不起作用 - Windows Vista - .NET 3.5
不起作用 - Windows Server 2008 - .NET 3.5
不起作用 - Windows 7 Beta - .NET 3.5 SP1

试过:

  • 来自here的一堆东西,没有任何帮助。
  • 使用WebClient,没有任何改变。
  • 调整这些options,但未注意到任何显着差异。
  • 尝试WireShark。一个非常好的工具。

[解决。有点]
我忘了提,但是Uri是https ...我试过http而且它有效。不敢相信,我没有早点尝试...... 不过,如果有人能在这整个情况下发光,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

我的第一个攻击计划是使用WireShark来查看每种情况下网络级别发生的情况。看看每台机器发送的是什么。

另外,您已经注意到操作系统之间存在差异,但它们是否都安装了完全相同的.NET版本(直到SP)?

答案 1 :(得分:1)

GET是否有效?也许这是代理配置问题(proxycfg等)。

另外 - 为了简化事情(减少未知数),请考虑使用WebClient来发布帖子:

using (WebClient client = new WebClient())
{
    client.Headers.Add("content-type","application/x-www-form-urlencoded");
    client.UploadData(address, data);
    // or more simply
    client.UploadValues(address, nameValuePairs);
}

答案 2 :(得分:0)

尝试调整以下一个或多个选项:

  • SendChucked
  • AllowAutoRedirect
  • TransferEncoding

还要尝试注意它们与各种配置之间的差异。

相关问题