1

我已经通过互联网和 Stack Overflow 搜索此问题的解决方案,并尝试了各种解决方案,但都没有奏效。

基本上,我有一个用 VB.NET 编写的 Windows 应用程序,当单击按钮时,它会执行以下操作:

 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim data As Byte() = Encoding.UTF8.GetBytes("Some data message")

    Dim myHttpWebRequest As HttpWebRequest = HttpWebRequest.Create("https://SomeDomain.com/sandbox/update")

    'If required by the server, set the credentials.
    'myHttpWebRequest.Credentials = CredentialCache.DefaultCredentials

    Dim cert As X509Certificate = X509Certificate.CreateFromCertFile("C:\Program Files (x86)\Certificates\somecertificate.cer")
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    myHttpWebRequest.ClientCertificates.Add(cert)

    myHttpWebRequest.ContentType = "application/json;profile=https://SomeDomain.com/update.json"

    myHttpWebRequest.Method = "POST"

    'WK 26/01/2017 - "2834"
    myHttpWebRequest.ContentLength = data.Length

    Dim oRequestStream = myHttpWebRequest.GetRequestStream()

    oRequestStream.Write(data, 0, data.Length)

    ' Get the response.
    Dim oWebResponse As WebResponse = myHttpWebRequest.GetResponse()

    ' Display the status.
    MsgBox(CType(oWebResponse, HttpWebResponse).StatusDescription)

    ' Get the stream containing content returned by the server.
    Dim oResponseStream As Stream = oWebResponse.GetResponseStream()

    ' Open the stream using a StreamReader for easy access.
    Dim oStreamReader As New StreamReader(oResponseStream)

    ' Read the content.
    Dim oResult As String = oStreamReader.ReadToEnd()

    ' Display the content.
    MsgBox(oResult)

    ' Clean up the streams and the response.
    oStreamReader.Close()
    oResponseStream.Close()

End Sub

但是,它在此行上不断抛出“您必须在调用 [Begin]GetResponse 之前将 ContentLength 字节写入请求流”异常:

 Dim oWebResponse As WebResponse = myHttpWebRequest.GetResponse()

奇怪的是,这段代码可以在同一网络上的不同机器上运行!唯一的区别是机器是32位,我的是64位,不确定是否相关。

我对 VB.NET 并不陌生,但之前没有使用过 HTTPWebRequest,基本上我是在尝试向 URL 发送一些更新并尝试返回结果以查看它是否成功。它需要将本地证书存储在我的机器上。

当我将 URL 域更改为“www.google.com”之类的内容时,它可以正常工作,但显然这不是我想要发布的 URL。

我只是不明白它是如何在一台机器上工作的,而不是另一台机器上。

我已经尝试了其他用户在类似帖子中使用“使用”关键字提出的建议:

 Using oRequestStream = myHttpWebRequest.GetRequestStream()
            oRequestStream.Write(data, 0, data.Length)
        End Using

但随后我收到“远程服务器返回错误:(400)错误请求。” GetResponse 行上的异常。

我还尝试将以下内容添加到配置文件中:

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="104857600" />
        </requestFiltering>
    </security>
</system.webServer>

但没有任何区别。

请有人可以帮助我并给我一些建议。可能与机器上的编码差异有关吗?

谢谢你。

4

0 回答 0