【问题标题】:System.Text.Encoding.UTF8.GetBytes introducing weird characterSystem.Text.Encoding.UTF8.GetBytes 引入奇怪的字符
【发布时间】:2026-02-09 07:10:01
【问题描述】:

使用此对客户端 Web 服务执行 PUT

using System;
using System.IO;
using System.Net;

class Test
{
    static void Main()
    {
        string xml = "<xml>...</xml>";
        byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/");
        request.Method = "PUT";
        request.ContentType = "text/xml";
        request.ContentLength = arr.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(arr, 0, arr.Length);
        dataStream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string returnString = response.StatusCode.ToString();
        Console.WriteLine(returnString);
    }
}

感谢this SO answer

如果我在 fiddler 中查看请求,我的帖子请求末尾有一个奇怪的字符 &lt;/xml&gt; 看起来像一个正方形[怀疑它是 BOM]

不确定它是如何引入我的字符串的。

【问题讨论】:

  • 默认的UTF8.GetBytes 不包括 BOM,如果您要求它添加到数组的前面而不是末尾。您发布的代码在我的测试中不包含“奇怪字符”,因此发生了其他事情。你还对arr 做其他事情吗?复制“奇怪的字符”并在十六进制编辑器中查看。
  • 如何创建 xml 字符串?例如,如果您使用的是 XmlWriter,那么您需要这样设置:new XmlWriterSettings { Encoding = new UTF8Encoding(false) }

标签: c#


【解决方案1】:

使用new UTF8Encoding(false).GetBytes(xml);

UTF8Encoding Constructor (Boolean):初始化 UTF8Encoding 类的新实例。一个参数指定是否提供 Unicode 字节顺序标记。

【讨论】:

  • 试过了,但奇怪的正方形仍然存在于提琴手中我的 xml 数据的末尾。