Monday, March 23, 2009

 

REST web service client in C#

I started writing a new web service at work. I've read a lot about REST and many of the principles resonated with me, so figured I'd give it a spin. It's amazing how little code there is out there. I found one very young view/controller framework for PHP. I found a couple of blog posts for C#.

This code will work with .NET 2.0. 3.5 and WCF may have some new methods for doing this, but it's shocking how little code there is out there for dealing with REST even today. Hopefully this helps someone. I'm putting it out as public domain but if you use it, it would be nice if you'd throw me a comment.

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;

using System.Web;

 

class Simple_REST

{

    public static string Get_URI(string uri)

    {

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);

        HttpWebResponse response = (HttpWebResponse)req.GetResponse();

        Stream responseStream = response.GetResponseStream();

        StreamReader reader = new StreamReader(responseStream);

 

        string responseString = reader.ReadToEnd();

 

        reader.Close();

        responseStream.Close();

        response.Close();

 

        return responseString;

    }

    public static string Post_URI(string uri, Dictionary<string, string> postDataDictionary)

    {

        string postData = "";

        foreach (KeyValuePair<string, string> kvp in postDataDictionary)

        {

            postData += string.Format("{0}={1}&", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value));

        }

        postData = postData.Remove(postData.Length - 1); // remove the trailing ampersand

 

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);

        req.Method = "POST";

        byte[] postArray = Encoding.UTF8.GetBytes(postData);

        req.ContentType = "application/x-www-form-urlencoded";

        req.ContentLength = postArray.Length;

 

        Stream dataStream = req.GetRequestStream();

        dataStream.Write(postArray, 0, postArray.Length);

        dataStream.Close();

 

        HttpWebResponse response = (HttpWebResponse)req.GetResponse();

        Stream responseStream = response.GetResponseStream();

        StreamReader reader = new StreamReader(responseStream);

 

        string responseString = reader.ReadToEnd();

 

        reader.Close();

        responseStream.Close();

        response.Close();

 

        return responseString;

    }

}


This page is powered by Blogger. Isn't yours?