xml - 400 错误请求:XML 文档中存在错误 (1, 1254) 消息显示不正确的行号
问题描述
我正在使用 HttpWebRequest 和 HttpWebResponse 从我的应用程序向外部 API 发送请求。
每当由于 XML 节点中传递的某些错误值而导致 XML 请求出错时,就会出现 400 Bad request 错误响应,并且错误消息是“XML 文档中存在错误 (51, 14)”。问题是如果请求 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
谢谢
解决方案
最后,我可以找到并解决这个问题。问题出在我试图发送的请求 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
推荐阅读
- visual-studio-2019 - Visual Studio 2019 IntelliTest 与 .NET Core、.NET Standard 的兼容性?
- python - 如果满足条件,如何交换 Nx2 numpy 数组的行的元素?
- javascript - const [a, b, c] = array 有什么区别?和 const {a, b, c} = 数组;
- security - Microsoft Identity Platform (/common/oauth2/v2.0/token) 上格式无效的 oAuth2.0 access_token
- mingw - MinGW 无法为导出的函数添加前缀 _impl_
- oracle-apex - 刷新后禁用页面项目不起作用
- python - Django 静态文件在根目录中时不加载
- java - Spring JPA 通过从 POST 请求正文中获取的列和值查询数据库
- regex - 如何批量删除 Google 表格中的单个数字
- python - 从系统中删除 node.js 后:ERROR:root:code for hash md5 was not found