Monday, March 23, 2009
REST web service client in C#
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;
}
}
Most of mine is adapted from MSDN so I imagine theirs was poached from the same place.
Thanks
Cheapest dedicated hosting
<< Home