gpt4 book ai didi

.net - UrlEncode .net 在字符串末尾添加 %00 个字符

转载 作者:行者123 更新时间:2023-12-01 11:50:30 25 4
gpt4 key购买 nike

当我在某些情况下对字符串(即 xml 文件)进行 urlEncode 时,它​​会在文件末尾添加 %00 字符。我想知道为什么会发生这种情况以及是否可以阻止(我总是可以删除 %00 字符)。 xml 文件是使用 xmlwriter 创建的。奇怪的是我使用相同的代码创建其他 xml 文件,并且在对它们进行编码后它不会添加 %00 个字符。

示例:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE peticion >
<peticion>
<nombre>Info hotel</nombre>
<agencia>HOTUSA</agencia>
<tipo>15</tipo>
</peticion>

编辑:创建 xml 这就是我所做的。

Dim xmlWriterSettings As New System.Xml.XmlWriterSettings
With xmlWriterSettings
.Encoding = Encoding.GetEncoding("iso-8859-1")
.OmitXmlDeclaration = False
.Indent = True
End With

Dim ms As New IO.MemoryStream

Using writer As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(ms, xmlWriterSettings)
With writer
.WriteDocType("peticion", Nothing, Nothing, Nothing)
.WriteStartElement("peticion")
.WriteElementString("nombre", "Info hotel")
.WriteElementString("agencia", "HOTUSA")
.WriteElementString("tipo", "15")
.WriteEndElement()
End With
End Using

Dim xml As String = Encoding.GetEncoding("iso-8859-1").GetString(ms.GetBuffer)

Dim XmlEncoded As String = HttpUtility.UrlEncode(xml)

XmlEncoded 包含:

%3c%3fxml+version%3d%221.0%22+encoding%3d%22iso-8859-1%22%3f%3e%0d%0a%3c!DOCTYPE+peticion+%3e%0d%
0a%3cpeticion%3e%0d%0a++%3cnombre%3eInfo+hotel%3c%2fnombre%3e%0d%0a++%3cagencia%3eHOTUSA%3c%
2fagencia%3e%0d%0a++%3ctipo%3e15%3c%2ftipo%3e%0d%0a%3c%2fpeticion%3e%00%00%00%00%00%00%00%00%00%
00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%
00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%
00%00%00%00%00%00%00%00%00%00%00%00%00%00

所有这些 %00 来自哪里?

最佳答案

关于MemoryStream.GetBuffer的评论提供适当的指导:

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

像这样修改你的代码:

Dim xml As String = Encoding.GetEncoding("iso-8859-1").GetString(ms.ToArray)

事实上,在这种情况下更好的选择是使用 StringBuilder :

Dim sb As New StringBuilder
Using writer As XmlWriter = XmlWriter.Create(sb, xmlWriterSettings)
' ...
End Using

Dim xml as String = sb.ToString()

关于.net - UrlEncode .net 在字符串末尾添加 %00 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11671972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com