Thursday, April 25, 2013

Client application to test RESTful Service


In my in my previous post “how to test restful service” I perform testing of RESTful service using a tool called “Fiddler”. Similarly you can create your own tool to test the restful service with full control over request/response.

Here I created a client application with a generic class to request/response from the Restful service. So instead of fiddler we can use this client application to test the service.

In that client application I used HttpWebRequest class to communicate with RESTful service similarly HttpWebRequest can be used for request/response from the internet in a protocol-agnostic manner.

Using HttpWebRequest request can be sent from an application to a particular URI, such as Web API, Web Page or server. HttpWebRequest class provides support for the properties and methods defined in WebRequest. 

WebRequest are typically registered to handle a specific protocol such as Http(s) or FTP(s).

Here in below example I am using a console application to handle request/response for RESTful service.

Step 1: Simple Create a console application as shown in screenshot below



Step 2: Write the following code in WebApiCaller.cs class



#region Comment Header
//***********************************************************************************
//*** Class: WebApiCaller
//*** Description: contains the implementation for request/response over http. Mainly for RESTful service.
//*** Source: WebApiCaller.cs
//*** Author: Sandeep Kumar

//***********************************************************************************
#endregion Comment Header

using System;
using System.IO;
using System.Net;
using System.Text;

namespace SerivceClient.Utility
{
    public class WebApiCaller
    {
        private readonly HttpWebRequest _request;

        /// <summary>
        /// To get the processed response as property
        /// </summary>
        public string ResponseFromServer { get; private set; }

        /// <summary>
        /// To know the status of request sent.
        /// </summary>
        public int Status { get; private set; }

        /// <summary>
        /// To get the request status message.
        /// </summary>
        public string Message { get; private set; }

        /// <summary>
        /// Set the Request Timeout in seconds
        /// </summary>
        public int Timeout { get; set; }

        /// <summary>
        /// Request content
        /// </summary>
        public string Content { getset; }


        public WebApiCaller(string url)
        {
            _request = (HttpWebRequest)WebRequest.Create(url);
        }

        public WebApiCaller(string url, string method)
            : this(url)
        {
            if (method.Equals("GET") || method.Equals("POST") || method.Equals("PUT") || method.Equals("DELETE"))
            {
                _request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
        }

        public WebApiCaller(string url, string method, string data)
            : this(url, method)
        {
            Content = string.IsNullOrEmpty(data) ? "" : data;
         
        }

        public WebApiCaller(string url, string method, string data, string contentType)
            : this(url, method, data)
        {
            if (!string.IsNullOrEmpty(contentType))
                _request.ContentType = contentType;
        }


        public WebApiCaller(string url, string method, string data, string contentType,  int timeout)
            : this(url, method, data, contentType)
        {

            if (timeout != 0)
            {
                Timeout= timeout ;
            }
          
        }


        public string GetResponse()
        {

            // Get the original response.
            HttpWebResponse response = null;
            StreamReader reader = null;

            try
            {

                Content = string.IsNullOrEmpty(Content) ? "" : Content;

                if (Content.IndexOf("<?xml") < 0)
                    Content = @"<?xml version=""1.0""?>" + Content;

                byte[] byteArray = Encoding.ASCII.GetBytes(Content);

                _request.KeepAlive = false;

                if (Timeout != 0 )
                {
                    //Also convert the timeout in milliseconds from secnonds.
                    _request.Timeout = Timeout * 1000;
                }

                // Set the ContentLength property of the WebRequest.
                _request.ContentLength = byteArray.Length;

                // Get the request stream and  Write the data to the request stream.
                _request.GetRequestStream().Write(byteArray, 0, byteArray.Length);


                response = (HttpWebResponse)_request.GetResponse();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Status = (int)response.StatusCode;
                    Message = response.StatusDescription;
                }
                else
                {
                    // Get the stream containing all content returned by the requested server.
                    Status = 0;
                    Message = "OK";
                    reader = new StreamReader(response.GetResponseStream());
                    // Read the content fully up to the end.
                    ResponseFromServer = reader.ReadToEnd();
                }

            }
            catch (Exception ex)
            {
                Status = 99;
                Message = ex.Message;
                ResponseFromServer = "";
            }
            finally
            {
                // Clean up the streams.
                if (reader != null) reader.Close();

                if (response != null) response.Close();
            }

            return ResponseFromServer;

        }

    }
}


Step 3: Call this class from your client form. I just took a very simple example in Program.cs to request/response from RESTful service.

using System;
using SerivceClient.Utility;

namespace SerivceClient
{
    class Program
    {
        static void Main(string[] args)
        {

            //assign the URI
            string serviceUri = @"http://localhost:39478/MyPosts.svc/Api/interface";

            string content = @"Hello, This is my first test to post data over restful service using client";

            //Create the

           // Console.WriteLine("Service URI {0}",serviceUri);
            Console.WriteLine("Request Content {0}", content);

            //create object  of WebApiCaller class
            var caller = new WebApiCaller(serviceUri, "POST",content);

           //Get the response received from RESTful service
            Console.WriteLine("Response: {0}", caller.GetResponse());
           
            Console.Read();

        }
    }
}




And get the response from GetResponse() method. If you also check the caller.Status before finally manage the response. And the status will be Zero for successful response.





Post a Comment