How to call restful web service using http webrequest
Call Restful web service using Httpwebrequest
In This article am going explain about how to call the restful web service using the Httpwebrequest
WCF Restful service
In This article am going explain about how to call the restful web service using the Httpwebrequest
WCF Restful service
Contract
[ServiceContract]
public interface IRestService
{
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/MyServiceMethod")]
[OperationContract]
void MyServiceMethod(PostedInformation postedInformations);
}
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
}
{
//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; }
[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 Rest service using HTTPWebRequest
var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("you object to be serialize" ));
//Passyour service url to the create method
var req =
HttpWebRequest.Create(“http://localhost/MyServer/YourServiceName.svc/MyServiceMethod);
req.ContentType = “application/json”;
req.ContentLength = dataToSend.Length;
req.Method = “POST”;
req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = req.GetResponse();
//Passyour service url to the create method
var req =
HttpWebRequest.Create(“http://localhost/MyServer/YourServiceName.svc/MyServiceMethod);
req.ContentType = “application/json”;
req.ContentLength = dataToSend.Length;
req.Method = “POST”;
req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = req.GetResponse();
I hope this will helps
Labels:
WCF