Call Restful Service using HttpWebRequest and Post data

Introduction

This article helps  you call Restful service using HttpWebRequest and Post Data to a particular service.The below demonstrate a sample restful service in WCF and call as HttpWebRequest.

WCF Restful Service Source Code

Contract

[ServiceContract]
public interface IRestService
{
[WebInvoke(Method = “POST”, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = “/MyServiceMethod”)]
[OperationContract]
void MyServiceMethod(PostedInformation postedInformations);
}

Implementation

public void MyServiceMethod(PostedInformation postedInformations)
{
//do implemention code here
}

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

}

Calling the service using HttpWebRequest

PostedInformation postedInformations = new PostedInformation()
{
SenderEmail = “aaa@bbb.com”,
SenderFullName = “test”,
To = new List<string>() { “ccc@eee.com” }
};

var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postedInformations ));
//Passyour service url to the create method
var req =
HttpWebRequest.Create(“http://localhost/MyServer/YourServiceName.svc/MyServiceMethod&#8221;);
req.ContentType = “application/json”;
req.ContentLength = dataToSend.Length;
req.Method = “POST”;
req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = req.GetResponse();

Enjoy coding…

4 thoughts on “Call Restful Service using HttpWebRequest and Post data

  1. when i tried like this ,getting error like ‘The remote server returned an error: (400) Bad Request.’ this error getting when i was mentioned HttpWebRequest.Create Like HttpWebRequest.Create(“http://localhost:27346/Service1.svc/MyServiceMethod&#8221”);

    but when i removed ‘&#8221’ this text from the ulr

    Getting error like

    The remote server returned an error: (415) Cannot process the message because the content type ‘application/json’ was not the expected type ‘text/xml; charset=utf-8’..

    any changes need to make in web config file ?

  2. It get the same error: The remote server returned an error: (400) Bad Request. I think me and Juan are missing something.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s