.NET: Posting Xml to a web-server? -
what proper way post xmldocument web-server? here skeleton function:
public static void postxml(xmldocument doc, string url) { //todo: write }
right use:
//warning: not use postxml implmentation //it doesn't adjust xml match encoding used webclient public static void postxml(xmldocument doc, string url) { using (webclient wc = new webclient()) { wc.uploadstring(url, documenttostr(doc)); } }
where documenttostr
valid , correct method:
/// <summary> /// convert xmldocument string /// </summary> /// <param name="doc">the xmldocument converted string</param> /// <returns>the string version of xmldocument</returns> private static string documenttostr(xmldocument doc) { using (stringwriter writer = new stringwriter()) { doc.save(writer); return writer.tostring(); } }
the problem implementation of postxml
posts string exactly is. means (in case) http request is:
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>
you'll notice xml declaration has incorrect encoding:
<?xml version="1.0" encoding="utf-16"?>
the webclient
not sending request in utf-16
unicode, how strings in .net stored. don't know encoding used webclient
.
the http post of xml needs encoded, happens during call to:
save(textwriter)
during call save
xmldocument
object adjust xml-declaration based on encoding
of textwriter
being asked save to. unfortunately webclient
doesn't expose textwriter
can save xmldocument to.
see also
- post xml .net web service
- http post of xml string , save .xml on server (django/gae)
- send xml via http post ip:port
- msdn: xmldocument.save method (textwriter)
- sending gzipped data in webrequest?
- c# web request post encoding question
- getrequeststream throws timeout exception randomly
- writing xml utf-8 encoding using xmltextwriter , stringwriter
there's solution. subclass stringwriter:
public class stringwriterwithencoding : stringwriter { encoding encoding; public stringwriterwithencoding (stringbuilder builder, encoding encoding) :base(builder) { this.encoding = encoding; } public override encoding encoding { { return encoding; } } }
Comments
Post a Comment