Monday, April 28, 2008

Post Http request in code behind example

public XmlDocument Send(string url, XmlDocument reqdoc)
{
//Start by creating the request using given URL
  HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
  httpReq.Method = @"POST";
  httpReq.ContentType = @"text/xml"; //Using XML
  httpReq.Timeout = 600000;//10 minutes (in milliseconds)
  httpReq.KeepAlive = false;

  Stream strm = httpReq.GetRequestStream();
  reqdoc.Save(strm);
  strm.Close();
//Create HttpWebRewponse to handle the result
  HttpWebResponse resp = (HttpWebResponse)httpReq.GetResponse();

  StreamReader srdr = new StreamReader(resp.GetResponseStream(),Encoding.GetEncoding("UTF-8"));
  string xmlstr = srdr.ReadToEnd();

  resp.Close();

  respdoc = new XmlDocument();

  try
  {
    StringBuilder sb = new StringBuilder(xmlstr);
//Remove undefined chars
    for(int c=0; c<sb.Length; c++)
    {
      if (sb[c]<'\x20')
      {
        sb[c]='\x20';
      }
    }

    respdoc.LoadXml(sb.ToString());

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

No comments: