通过http发送xml会丢失缩进

问题描述 投票:0回答:2

我有一个相当大的XML文件,我想通过http发送到设备。我正在使用的方法是创建Xmldocument(称为doc),将outerXML转换为字符串,并使用HttpWebResponse发送它。

这是XML的一部分:

  <MotionDetection>
   <id>1</id>
   <enabled>true</enabled>
   <samplingInterval>2</samplingInterval>
   <startTriggerTime>500</startTriggerTime>
   <endTriggerTime>500</endTriggerTime>
   <regionType>grid</regionType>
     <Grid>
      <rowGranularity>15</rowGranularity>
      <columnGranularity>22</columnGranularity>
  </Grid>
</MotionDetection>

问题:每当我通过互联网发送我的代码时,它都不接受它(给我一个错误的请求响应)因为xml缺少“indents”或vbCrlfs导致wireshark嗅探器看到它像xml而不是一堆串在一起的碎片。

有没有办法使用httpwebresponse发送它,以便那些留在请求中?当然,除了打破字符串并通过“手”插入它之外?

这是我当前的代码,因为我也尝试使用上传客户端而不是httpwebrequest。

        Dim doc As New Xml.XmlDocument
        doc.Load("test.xml")
       Try
            Dim url = "http://" & currentCamera.ipaddr & "/Custom/Motion"
            Dim client As New WebClient
            client.Credentials = New Net.NetworkCredential(currentCamera.Username, currentCamera.Password)
            Dim sentXml As Byte() = System.Text.Encoding.ASCII.GetBytes(doc.OuterXml)
            Dim response2 As Byte() = client.UploadData(url, "PUT", sentXml)

        Catch ex As Exception

        End Try
xml vb.net
2个回答
0
投票

我发现的解决方案与编码有关。特别是这一行:

  Dim sentXml As Byte() = System.Text.Encoding.ASCII.GetBytes(doc.OuterXml)

通过将编码从ASCII更改为UT8,设备接受了xml并实现了更改。即

   Dim sentXml As Byte() = System.Text.Encoding.UTF8.GetBytes(doc.OuterXml)

显然,这是网络设备更容易接受的方法。


0
投票

删除空格不应该破坏您的XML文件,但编码错误。顺便说一句,删除空格也不错,它会为你节省一些网络数据。有效载荷越小越好。

© www.soinside.com 2019 - 2024. All rights reserved.