如何使用post方法调用Rest Web Service并在C#中发送xml数据

时间:2009-09-22 13:43:55

标签: c# xml rest post

我在这里要做的是使用xml数据向Rest Web服务发出请求。

这就是我现在所拥有但我不确定如何传递我的xml数据

            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 个答案:

答案 0 :(得分:6)

我使用WebClient类:

WebClient webClient = new WebClient();
using (webClient)
{
   requestInterceptor.OnRequest(webClient);
   var enc = new ASCIIEncoding();
   return enc.GetString(webClient.UploadData(uri, enc.GetBytes(dataAsString)));
}

答案 1 :(得分:5)

您正在做的事情没有根本错误,但您需要刷新/关闭请求流编写器。这可以通过using构造轻松完成,因为处理编写器也会刷新它:

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

然后,您需要调用GetResponse来实际执行请求:

req.GetResponse()

(请注意,从此返回的HttpWebResponse也是一次性的,所以不要忘记处置它。)