This blog is subject the DISCLAIMER below.

Tuesday, May 25, 2010

How to consume REST based-services?

Q. How to consume REST based-services?
Assume we have REST based-service contains method Add which takes two operands op1 and op2 and return the summation.

A. Create any project type (Console, Windows or even Web-based application)
Add using System.Net; using System.IO;
Write some code to consum the service
string parameters;
string response;
// Create the request obj
WebRequest request = WebRequest.Create("serviceURL/Add");
// Set values for the request back
request.Method = "POST"; //REST based-services using Post method
request.ContentType = "application/json"; //tells request the content typs is JSON
parameters = "{\"op1\":2,\"op2\":\"1\"}";
request.ContentLength = parameters.Length;
// Write the request
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
// Do the request to get the response
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
response = responseReader.ReadToEnd();
//response value should be 3 if you implement Add method correctly :))

1 comment:

Mohammed Hewedy said...

I think the title better to include the word "in .NET" :D

good article BTW