Friday, March 1, 2013

REST calls in CSharp

I needed to code set of REST calls in C# with a some specific requirements that prevented use of simpler WebClient API:


  • Setting the ContentType for "text/xml"
  • Support for GET, DELETE, and POST methods
  • The POST method had to submit data (an XML fragment) and also returned data (XML fragment)

Following is what I hacked out and documenting here so I don't have to look it up again.


XmlDocument RestGet(string uri)
{
    XmlDocument doc = new XmlDocument();

    HttpWebRequest request = 
     (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.ContentType = "text/xml";

    HttpWebResponse response = 
     (HttpWebResponse)request.GetResponse();
    doc = new XmlDocument();
    doc.Load(response.GetResponseStream());
    response.Close();

    return doc;
}



static XmlDocument RestDelete(string uri)
{
    XmlDocument doc = new XmlDocument();

    HttpWebRequest request = 
     (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "DELETE";
    request.ContentType = "text/xml";

    HttpWebResponse response = 
     (HttpWebResponse)request.GetResponse();
    doc = new XmlDocument();
    doc.Load(response.GetResponseStream());
    response.Close();

    return doc;
}


static XmlDocument RestPost(string uri, string data)
{
    XmlDocument doc = new XmlDocument();

    HttpWebRequest request = 
     (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "POST";
    request.ContentType = "text/xml";

    System.Text.UTF8Encoding encoding = 
     new System.Text.UTF8Encoding();
    byte[] byte1 = encoding.GetBytes(data);
    request.ContentLength = byte1.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(byte1, 0, byte1.Length);
    requestStream.Close();

    HttpWebResponse response = 
     (HttpWebResponse)request.GetResponse();
    doc = new XmlDocument();
    doc.Load(response.GetResponseStream());
    response.Close();

    return doc;
}