What is the proper way to post an XmlDocument to a web-server? Here is the skeleton function:
public static void PostXml(XmlDocument doc, String url)
{
//TODO: write this
}
Right now i use:
//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));
}
}
Where DocumentToStr
is a perfectly valid and correct method:
/// <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();
}
}
The problem with my implementation of PostXml
is that it posts the String exactly as is. This means that (in my case) the http request is:
POST http://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>
You'll notice that the xml declaration has an incorrect encoding:
<?xml version="1.0" encoding="utf-16"?>
The WebClient
is not sending the request in utf-16
unicode, that was how Strings in .NET are stored. i don't even know the encoding used by the WebClient
.
The http post of the xml needs to be properly encoded, which normally happens during a call to:
Save(textWriter)
During a call to Save
the XmlDocument
object will adjust the xml-declaration based on Encoding
of the TextWriter
it is being asked to save to. Unfortunately WebClient
doesn't expose a TextWriter
that i can save the XmlDocument to.
See also
- 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