tags:

views:

898

answers:

2

Hi everyone,

What i am trying to do here is make post request to Rest webserivce with xml data.

this is what i have right now but i am not sure how to pass my xml data

            XElement xml = new XElement("MatchedOptions",
               from m in _matchedOptionsList
               select new XElement("Listing",
                       new XElement("DomainID", _trafficCopInputs.DomainID),
                       new XElement("AdSource", _trafficCopInputs.AdSource),
                       new XElement("Campaign", _trafficCopInputs.Campaign),
                       new XElement("AdGroup", _trafficCopInputs.AdGroup),
                       new XElement("RedirectURL", m.RedirectPath),
                       new XElement("FunnelKeyword", m.FunnelKeyword)));

            HttpWebRequest req = WebRequest.Create("http://something.com/")
                 as HttpWebRequest;


            req.Method = "POST";
            req.ContentType = "text/xml";
            req.ContentLength = 0;
            StreamWriter writer = new StreamWriter(req.GetRequestStream());
            writer.WriteLine(xml.ToString());
+2  A: 

I use the WebClient class:

WebClient webClient = new WebClient();
using (webClient)
{
   requestInterceptor.OnRequest(webClient);
   var enc = new ASCIIEncoding();
   return enc.GetString(webClient.UploadData(uri, enc.GetBytes(dataAsString)));
}
Grzenio
I would suggest defining the WebClient at the top of the using statement. That way the name webClient is local to the using block and there's no risk of calling methods on webClient after it's been disposed.
ctford
+3  A: 

There's nothing fundamentally wrong with what you're doing, but you need to flush/close the request stream writer. This can be easily done with the using construct as disposing the writer also flushes it:

using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
{
    writer.WriteLine(xml.ToString());
}

You then need to call GetResponse to actually execute the request:

req.GetResponse()

(Note that the HttpWebResponse returned from this is also disposable, so don't forget to dispose that too.)

Greg Beech