12.1. Using REST in C#

Issuing HTTP GET Requests
The key classes here are HttpWebRequest and HttpWebResponse from System.Net.

The following method issues a request and returns the entire response as one long string:

static string HttpGet(string url) {
  HttpWebRequest req = WebRequest.Create(url)
                       as HttpWebRequest;
  string result = null;
  using (HttpWebResponse resp = req.GetResponse()
                                as HttpWebResponse)
  {
    StreamReader reader =
        new StreamReader(resp.GetResponseStream());
    result = reader.ReadToEnd();
  }
  return result;
}

Remember that if the request URL includes parameters, they must be properly encoded (e.g., a space is %20, etc.). The System.Web namespace has a class called HttpUtility, with a static method called UrlEncode for just such encoding.

Issuing HTTP POST Requests
URL encoding is also required for POST requests -- in addition to form encoding, as shown in the following method:

static string HttpPost(string url, 
    string[] paramName, string[] paramVal)
{
  HttpWebRequest req = WebRequest.Create(new Uri(url)) 
                       as HttpWebRequest;
  req.Method = "POST";  
  req.ContentType = "application/x-www-form-urlencoded";

  // Build a string with all the params, properly encoded.
  // We assume that the arrays paramName and paramVal are
  // of equal length:
  StringBuilder paramz = new StringBuilder();
  for (int i = 0; i < paramName.Length; i++) {
    paramz.append(paramName[i]);
    paramz.append("=");
    paramz.append(HttpUtility.UrlEncode(paramVal[i]));
    paramz.append("&");
  }

  // Encode the parameters as form data:
  byte[] formData =
      UTF8Encoding.UTF8.GetBytes(paramz.toString());
  req.contentLength = formData.Length;

  // Send the request:
  using (Stream post = req.GetRequestStream())  
  {  
    post.Write(formData, 0, formData.Length);  
  }

  // Pick up the response:
  string result = null;
  using (HttpWebResponse resp = req.GetResponse()
                                as HttpWebResponse)  
  {  
    StreamReader reader = 
        new StreamReader(resp.GetResponseStream());
    result = reader.ReadToEnd();
  }

  return result;
}

For more examples, see this page on the Yahoo! Developers Network.

7 comments:

Simon said...

Your code for GET request has a slight typo - instead of "response" it should say "result".

Regards
Simon.

Dr. M. Elkstein said...

Thanks Simon! I've fixed it now.

Amr Eldib said...

"params" is a keyword in C# now.
http://msdn.microsoft.com/en-us/library/w5zay9db%28VS.71%29.aspx

Maybe you could modify the code (POST example) to avoid using it.

Dr. M. Elkstein said...

Thanks Amr! I've changed it to "paramz". Hopefully, that won't become a keyword anytime soon...

Andy said...

Awesome! Thanks Dr. M!

Kapil said...

Great work Elkstein

Shiv said...

Very well written...thanks!