400错误请求:XML文档(1,1254)消息中显示错误,显示错误的行号

时间:2018-04-28 13:58:04

标签: xml post request httpwebrequest indentation

我正在使用HttpWebRequest和HttpWebResponse从我的应用程序向外部API发送请求。

每当XML请求中由于XML节点中传递了一些错误值而导致错误时,就会出现400 Bad请求错误响应,并且错误消息为" XML文档中存在错误(51,14 )&#34 ;.问题是如果请求XML中存在错误,响应XML应显示具有正确行号的错误消息。但是我收到错误消息,行号不正确,并且始终是" XML文档中存在错误(1,1254)"。第1行实际上没有错误。由于此问题,我无法在进行故障排除时指出错误。

您能否帮助我如何使用XML中的正确行号获取响应。

以下是我在vb中的现有代码,用于将请求发送给API。

Dim Wreq As HttpWebRequest
Dim MyURI As String = String.Empty
Dim bytes() As Byte
Try
MyURI = p_strURL
Wreq = HttpWebRequest.Create(MyURI)
Wreq.Method = "POST"
bytes = System.Text.Encoding.UTF8.GetBytes(pi_strRequestXML)
Wreq.ContentLength = bytes.Length 'pi_strRequestXML.Length
Wreq.ContentType = "application/x-www-form-urlencoded"
Wreq.KeepAlive = False
Wreq.Headers.Add("Authorization", "bearer" + " " + strAccessToken)
Using OutputStream As StreamWriter = New StreamWriter(Wreq.GetRequestStream())
OutputStream.Write(pi_strRequestXML)
End Using

Using Wres As HttpWebResponse = Wreq.GetResponse()
Using loResponseStream As StreamReader = New StreamReader(Wres.GetResponseStream())
oResponse = loResponseStream.ReadToEnd()
End Using
End Using
Return oResponse
Catch e As WebException
Throw
Catch objSysEx As Exception
Throw
Finally

End Try

由于

1 个答案:

答案 0 :(得分:1)

最后,我可以找到并解决这个问题。问题出在我试图发送的请求XML中。请求XML格式不正确,因此如果XML中存在错误,则显示不适当的行号。解决方案是使用适当的缩进格式化请求XML。 下面是我用来制作格式良好的XML的代码。

Using sw As New StringWriterWithEncoding(Encoding.UTF8)
    Using tw As New XmlTextWriter(sw)
     'tw.Settings.Encoding = Encoding.UTF8
      tw.Formatting = Xml.Formatting.Indented
      tw.Indentation = 4
      Dim docu As New XmlDocument
      docu.LoadXml(strXML)
      docu.Save(tw)
      strProfileXML = Convert.ToString(sw)
   End Using
End Using

在上面的代码中, StringWriterWithEncoding是用于使用UTF-8编码创建格式化XML的函数。如果没有使用此功能,则将使用UTF-16

创建XML

以下是用于设置XML

的编码的函数
Private NotInheritable Class StringWriterWithEncoding
        Inherits StringWriter
        Private ReadOnly m_encoding As Encoding
        Public Sub New(encoding As Encoding)
            m_encoding = encoding
        End Sub
        Public Overloads Overrides ReadOnly Property Encoding() As Encoding
            Get
                Return m_encoding
            End Get
        End Property
    End Class