C# Xml in Http Post Request Message Body
Asked Answered
C

2

12

I am looking for an example of how, in C#, to put a xml document in the message body of a http request and then parse the response. I've read the documentation but I would just like to see an example if there's one available. Does anyone have a example?

thanks

Consort answered 3/4, 2009 at 23:0 Comment(0)
F
31
private static string WebRequestPostData(string url, string postData)
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(url);

    req.ContentType = "text/xml";
    req.Method = "POST";

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
    req.ContentLength = bytes.Length;

    using (Stream os = req.GetRequestStream())
    {
        os.Write(bytes, 0, bytes.Length);
    }

    using (System.Net.WebResponse resp = req.GetResponse())
    {
        if (resp == null) return null;

        using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
        {
            return sr.ReadToEnd().Trim();
        }
    }
}
Faultless answered 18/6, 2009 at 18:46 Comment(0)
R
5

You should use the WebRequest class.

There is an annotated sample available here to send data:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Residuary answered 3/4, 2009 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.