Cannot close stream until all bytes are written

2020-04-16 17:54发布

问题:

I am sending a POST request to an API server and I have reused code where I have successfully done this before on other servers and for some reason, which I cannot figure out why, it's not working. I get the error:

"Cannot close stream until all bytes are written."

even though I declared the content length correctly and I am not sure what I am missing here...

            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"

' //normally I just use request.contentlength = postbytes.length or 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

....

回答1:

The Exception is thrown because you are writing less bytes than the WebRequest expects. For example if you have set say 75 bytes in the ContentLength property and you write 69 bytes on the RequestStream and close it the exception will be thrown.



回答2:

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

changed my code as above