c# - HttpWebRequest 仅在 .NET 4.0 上运行

标签 c# vb.net .net-4.0 .net-3.5 httpwebrequest

我遇到了一个奇怪的问题,甚至是 WebRequest 的行为。首先,这是我正在尝试做的事情:

Dim req As HttpWebRequest = CType(Net.WebRequest.Create("https://cloud.myweb.de/myenginge/dostuff"), HttpWebRequest)

Dim inputString As String = "text=DoStuff"
Dim data As Byte() = System.Text.Encoding.ASCII.GetBytes(inputString)

req.Method = "POST"
req.Accept = "application/xml;q=0.9,*/*;q=0.8"

req.ContentType = "application/x-www-form-urlencoded"
req.ContentLength = data.Length

str2 = req.GetRequestStream()

str2.Write(data, 0, data.Length)
str2.Close()

Dim resp As HttpWebResponse = CType(req.GetResponse, HttpWebResponse)
str = resp.GetResponseStream()
buffer = New IO.StreamReader(str, System.Text.Encoding.ASCII).ReadToEnd

但是在我的编译设置中设置 .NET Frame 3.5 会导致超时:

str2 = req.GetRequestStream()

在设置框架版本 4.0 时,一切正常,没有任何超时问题。有人知道为什么会这样吗?我也试过 3.0,也没用。

(我在此示例中使用的是 VB.NET,但也欢迎使用 C# 解决方案。)

最佳答案

我猜您还有其他未处理的未处理请求。更新您的代码以在适用的情况下使用 using 语句(在处理任何实现 IDisposable 的对象时,您应该始终使用它)例如

using (var stream = req.GetRequestStream())
{
    ...
}

这将确保在进入下一个流之前可靠地关闭所有流。

更新

这绝对不是切换 .NET Framework 的问题,我将您的代码沙箱化到一个小型控制台应用程序中,并按如下方式重新编写代码(显然将您的 URL 换成另一个):

Dim request = CType(WebRequest.Create("https://cloud.myweb.de/myenginge/dostuff"), HttpWebRequest)
Dim data As Byte() = System.Text.Encoding.ASCII.GetBytes("text=DoStuff")
request.Method = WebRequestMethods.Http.Post
request.Accept = "application/xml;q=0.9,*/*;q=0.8"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = data.Length
Using inputStream = request.GetRequestStream()
    inputStream.Write(data, 0, data.Length)
End Using

Dim response = CType(request.GetResponse(), HttpWebResponse)
Dim buffer As String = ""
Using outputStream = response.GetResponseStream()
    Using streamReader = New StreamReader(outputStream, System.Text.Encoding.ASCII)
        buffer = streamReader.ReadToEnd()
    End Using
End Using
Console.WriteLine(buffer)

我每次都得到成功的回复。我在 .NET 4.0 和 3.5 下运行相同的代码。以下是每个请求的外观 Fiddler :

POST someurl HTTP/1.1
Accept: application/xml;q=0.9,/;q=0.8
Content-Type: application/x-www-form-urlencoded
Host: someurl
Content-Length: 12
Expect: 100-continue
Connection: Keep-Alive

text=DoStuff

关于c# - HttpWebRequest 仅在 .NET 4.0 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319891/

相关文章:

c# - 使用 Visual Studio 2010 为较旧的 .net 框架创建

c# - 登录后重定向 : Web. 配置

c# - 如何在 ASP.NET 中写入内存使用日志

vb.net - 正确使用 List.Exists 和 Predicates

在集合中找不到 MySQL 参数

multithreading - ConcurrentBag<T> 中的 Parallel.ForEach 是线程安全的

c# - 如何将 C# 类属性转换为 Json 文件

c# - 如何绑定(bind)位于隔离存储中的图像

vb.net - 在 VB.NET 中创建文本并将其附加到 txt 文件

wpf - 为什么 ICollectionView<T> 没有 .Net 接口(interface)?