【发布时间】:2011-04-22 12:00:14
【问题描述】:
将XmlDocument 发布到网络服务器的正确方法是什么?这是骨架函数:
public static void PostXml(XmlDocument doc, String url)
{
//TODO: write this
}
我现在使用:
//Warning: Do not use this PostXml implmentation
//It doesn't adjust the Xml to match the encoding used by WebClient
public static void PostXml(XmlDocument doc, String url)
{
using (WebClient wc = new WebClient())
{
wc.UploadString(url, DocumentToStr(doc));
}
}
DocumentToStr 是一个完全有效且正确的方法:
/// <summary>
/// Convert an XmlDocument to a String
/// </summary>
/// <param name="doc">The XmlDocument to be converted to a string</param>
/// <returns>The String version of the XmlDocument</returns>
private static String DocumentToStr(XmlDocument doc)
{
using (StringWriter writer = new StringWriter())
{
doc.Save(writer);
return writer.ToString();
}
}
我实现PostXml 的问题在于它按原样发布字符串完全。这意味着(在我的情况下)http请求是:
POST https://stackoverflow.com/upload.php HTTP/1.1
Host: stackoverflow.com
Content-Length: 557
Expect: 100-continue
<?xml version="1.0" encoding="utf-16"?>
<AccuSpeedData MACAddress="00252f21279e" Date="2010-10-07 10:49:41:768">
<Secret SharedKey="1234567890abcdefghijklmnopqr" />
<RegisterSet TimeStamp="2010-10-07 10:49:41:768">
<Register Address="total:power" Type="Analog" Value="485" />
<Register Address="total:voltage" Type="Analog" Value="121.4" />
<Register Address="total:kVA" Type="Analog" Value="570" />
</RegisterSet>
</AccuSpeedData>
您会注意到 xml 声明的编码不正确:
<?xml version="1.0" encoding="utf-16"?>
WebClient 没有以utf-16 unicode 发送请求,这就是.NET 中字符串的存储方式。我什至不知道 WebClient 使用的编码。
xml的http post需要正确编码,这通常发生在调用:
Save(textWriter)
在调用Save 期间,XmlDocument 对象将根据要求保存到的TextWriter 的Encoding 调整xml 声明。不幸的是,WebClient 没有公开我可以将 XmlDocument 保存到的TextWriter。
另见
- Post XML to .net web service
- HTTP Post of XML string and save it as .xml on server (django/GAE)
- Send XML via HTTP Post to IP:Port
- MSDN: XmlDocument.Save Method (TextWriter)
- Sending gzipped data in WebRequest?
- C# web request with POST encoding question
- GetRequestStream throws Timeout exception randomly
- Writing XML with UTF-8 Encoding using XmlTextWriter and StringWriter
【问题讨论】:
标签: .net xml xml-serialization xmlhttprequest