Total Pageviews

Wednesday, May 1, 2013

Call Restful Service using HttpWebRequest and Post data

        This article helps  you call Restful service using HttpWebRequest and Post Data to a particular service.

Our Restful Service

    public interface IOrionChatService

 [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/PushNotification")]
        void MyServiceMethod(PostedInformation postedInformations);

Service Implementation
  public void MyServiceMethod(PostedInformation postedInformations)
//do implemention code here


    public class PostedInformation 
        public List<string> To { get; set; }
        public string SenderEmail { get; set; }
        public string Subject { get; set; }
        public string SenderFullName { get; set; }


Calling our created Restful service from a Console application using HttpWebRequest

//Create a  new object of the class that we want to post

  PostedInformation postedInformations = new PostedInformation ()
               SenderEmail = "",
               SenderFullName = "test",
                To = new List<string>() { "" }
//Serialize the postedInformations to jSon using Newtonsoft.json. You can download dll from here //

 var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postedInformations ));
//Passyour service url to the create method
            var req = 
            req.ContentType = "application/json";
            req.ContentLength = dataToSend.Length;
            req.Method = "POST";
            req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
            var response = req.GetResponse();


No comments:

Post a Comment