我正在向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
...
答案 0 :(得分:12)
抛出Exception
因为您编写的字节数少于WebRequest
所需的字节数。例如,如果您在ContentLength
属性中设置了75个字节,并在RequestStream
上写入69个字节并关闭它,则会抛出异常。
答案 1 :(得分:9)
Dim writer As Stream = request.GetRequestStream()
writer.Write(postBytes, 0, postBytes.Length)
writer.Close()
按上述方式更改了我的代码