在写入所有字节之前无法关闭流

时间:2010-12-14 16:19:29

标签: vb.net visual-studio-2008

我正在向API服务器发送一个POST请求,我已经重新使用了我之前在其他服务器上成功完成此操作的代码,由于某种原因,我无法弄清楚为什么,它无效。我收到错误:

“在写入所有字节之前无法关闭流。”

即使我正确宣布内容长度,我也不确定我在这里缺少什么......

            data = data + "</posts>"
            Dim postBytes As [Byte]() = Encoding.UTF8.GetBytes(data)
            Thread.Sleep(10000)
            track = data
            If uri.Scheme = uri.UriSchemeHttps Then
                Dim request As HttpWebRequest = HttpWebRequest.Create(url)
                request.Method = "POST"

'//通常我只使用request.contentlength = postbytes.length或data.length

                request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(data)
                request.ContentType = "application/xml"
                request.KeepAlive = False
                request.Timeout = 120000
           request.Credentials = New  System.Net.NetworkCredential("xxxxxxxxxxxx",  "xxxxxxxxx")

                Using writer As New StreamWriter(request.GetRequestStream(), Encoding.UTF8)
                    writer.Write(postBytes)
                    writer.Flush()
                    writer.Close()
                End Using
                Using oResponse As HttpWebResponse = request.GetResponse()
                    Dim reader As New StreamReader(oResponse.GetResponseStream())
                    responseData = reader.ReadToEnd()
                    reader.Close()
                    oResponse.Close()
                End Using
                request.Abort()

            End If

        End If
    Catch e As WebException

...

2 个答案:

答案 0 :(得分:12)

抛出Exception因为您编写的字节数少于WebRequest所需的字节数。例如,如果您在ContentLength属性中设置了75个字节,并在RequestStream上写入69个字节并关闭它,则会抛出异常。

答案 1 :(得分:9)

 Dim writer As Stream = request.GetRequestStream()
                writer.Write(postBytes, 0, postBytes.Length)
                writer.Close()

按上述方式更改了我的代码