2011-02-19 54 views
0

呃,我不斷收到一個ProtocolViolationException「要寫入流的字節超過指定的Content-Length字節大小。在下面的代碼。Vb.Net - 寫入的字節超過XML中的內容長度字節

我試過設置Content-Length多種方式沒有成功。

Dim url = "https://domain.com" 
Dim req As WebRequest = WebRequest.Create(url) 
req.Method = "POST" 
req.ContentType = "application/xml" 

Dim utf8 As New UTF8Encoding() 
req.ContentLength = utf8.GetByteCount(xml.OuterXml) 

xml.Save(req.GetRequestStream()) // throws the exception 
req.GetRequestStream().Close() 

Dim httpResp As WebResponse = req.GetResponse() 
Dim stReader As StreamReader = New StreamReader(httpResp.GetResponseStream()) 
Dim strResponse As String 

strResponse = stReader.ReadToEnd() 

Console.WriteLine(strResponse) 

我試過設置使用xml.OutXML.Length

+0

如果您省略行,會發生什麼情況:req.ContentLength = utf8.GetByteCount(xml.OuterXml)? – CarneyCode 2011-02-19 07:07:59

+0

該API要求我發送有效的Content-Length標頭。 – doremi 2011-02-19 07:13:03

回答

1

WebClient嘗試內容長度,它使代碼更容易,它需要的正確的沖洗和處理所有流護理:

Dim xml As New XmlDocument 
xml.LoadXml("<foo>abc</foo>") 
Using client As WebClient = New WebClient 
    client.Headers.Item(HttpRequestHeader.ContentType) = "application/xml" 
    Dim data As Byte() = Encoding.UTF8.GetBytes(xml.OuterXml) 
    Console.WriteLine(Encoding.UTF8.GetString(client.UploadData("https://domain.com", data))) 
End Using 
相關問題