Monday, March 3, 2008

Post and receive XML to a URL

Here is a quick example of how to post and receive XML using HttpWebRequest:

//Some libraries that will be needed:
System.Net;
System.IO;
System.Xml;
System.Text;

public XmlDocument Send(string url, XmlDocument reqdoc)
{
//Setting up and posting request
  HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
  httpReq.Method = @"POST";
  httpReq.ContentType = @"text/xml";
  httpReq.Timeout = 600000; // 10 minutes (in milliseconds)
  httpReq.KeepAlive = false;

  Stream strm = httpReq.GetRequestStream();
  XmlDocument doc = new XmlDocument();
  doc.LoadXml("); //load xml
  doc.Save(strm); //strm will be the data to be sent
  strm.Close();

//Receiving result
  HttpWebResponse resp = (HttpWebResponse)httpReq.GetResponse();
  StreamReader srdr = new StreamReader(resp.GetResponseStream(),Encoding.GetEncoding("UTF-8"));
  string xmlstr = srdr.ReadToEnd();

  resp.Close();
  XmlDocument respdoc = new XmlDocument();
  try
  {
    StringBuilder sb = new StringBuilder(xmlstr);
    for(int c=0; c<sb.Length; c++)
    {
      if (sb[c]<'\x20')
      {
        sb[c]='\x20';
      }
    }

    respdoc.LoadXml(sb.ToString());
    string respXmlStr = respdoc.OuterXml;
  }
  catch(Exception e)
  {
    string msg = "Invalid XML response returned: " + e.Message;
    throw new Exception(msg,e);
  }

return respdoc;
}

No comments: