Tuesday, May 25, 2010

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) and add the below lines :

Code Snippet
  1. using System.Net;
  2. using System.IO;


B) Write some code to consume the service:

Code Snippet
  1. string parameters;
  2. string response;
  3. // Create the request obj
  4. WebRequest request = WebRequest.Create("serviceURL/Add");
  5. // Set values for the request back
  6. request.Method = "POST"; //REST based-services using Post method
  7. request.ContentType = "application/json"; //tells request the content typs is JSON
  8. parameters = "{\"op1\":2,\"op2\":\"1\"}";
  9. request.ContentLength = parameters.Length;
  10. // Write the request
  11. StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
  12. requestWriter.Write(parameters);
  13. requestWriter.Close();
  14. // Do the request to get the response
  15. StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
  16. response = responseReader.ReadToEnd();
  17. responseReader.Close();



Response value should be 3 if you implement Add method correctly :))

 

C# FastFood by :
Eng.Ramy Mahrous
http://ramymahrous.wordpress.com/about/



1 comments:

Anonymous said...

thx