Call Restful Service using HttpWebRequest and Post data


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


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


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 the service using HttpWebRequest

PostedInformation postedInformations = new PostedInformation()
SenderEmail = “”,
SenderFullName = “test”,
To = new List<string>() { “” }

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();

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: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s