5

我遇到了一个奇怪的问题,甚至是 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# 解决方案。)

4

2 回答 2

2

我的猜测是您还有其他一些尚未处理的请求。更新您的代码以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-活

文本=DoStuff

于 2012-07-03T23:06:08.333 回答
0

I would compare the IL code of your exe files using ILSpy.
Maybe an inspection on this level gives you an idea where things differ between the versions.

于 2012-07-04T08:58:48.277 回答