【发布时间】: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);
}
}
如果我在 fiddler 中查看请求,我的帖子请求末尾有一个奇怪的字符 </xml> 看起来像一个正方形[怀疑它是 BOM]
不确定它是如何引入我的字符串的。
【问题讨论】:
-
默认的
UTF8.GetBytes不包括 BOM,如果您要求它添加到数组的前面而不是末尾。您发布的代码在我的测试中不包含“奇怪字符”,因此发生了其他事情。你还对arr做其他事情吗?复制“奇怪的字符”并在十六进制编辑器中查看。 -
如何创建 xml 字符串?例如,如果您使用的是 XmlWriter,那么您需要这样设置:
new XmlWriterSettings { Encoding = new UTF8Encoding(false) }
标签: c#