2013-04-30 85 views
2

我创建了一个RESTful Web服务一样放心FUL web服务下面如何调用使用HttpWebRequest和POSTDATA

Opertation合同

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/PushNotification")] 
     [OperationContract] 
     void PushNotification(MailInformation mailInformations); 

MailInformations类

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

我怎么能使用HttpWebrequest调用此服务?

我的服务URL

本地主机/聊天/ ChatService.svc/PushNotification

+0

这是一项休息服务。我认为休息服务不代理 – JEMI 2013-04-30 12:39:42

回答

4
MailInformation mi = new MailInformation(){ 
    SenderEmail = "[email protected]", 
    Subject = "test", 
    To = new List<string>(){"[email protected]"} 
}; 

var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(mi)); 

var req = HttpWebRequest.Create("http://localhost/Chat/ChatService.svc/PushNotification"); 

req.ContentType = "application/json"; 
req.ContentLength = dataToSend.Length; 
req.Method = "POST"; 
req.GetRequestStream().Write(dataToSend,0,dataToSend.Length); 

var response = req.GetResponse(); 
+0

其中名称空间JsonConvert类? – JEMI 2013-04-30 12:44:25

+0

对不起..我用[Json.net](http://json.codeplex.com/)但你也可以使用[JavaScriptSerializer](http://msdn.microsoft.com/en-us/library/system。 web.script.serialization.javascriptserializer.aspx) – I4V 2013-04-30 12:51:53

+0

是的。我知道了。我试过Newtonsoft.Json – JEMI 2013-04-30 12:52:38

0

您可以保存自己使用HttpWebRequest,只是使用RestSharp的麻烦。

var client = new RestClient("http://localhost"); 
var request = new RestRequest("Chat/ChatService.svc/PushNotification"); 
RestResponse response = client.Execute(request); 
var content = response.Content; // raw content as string 
+0

如何发布数据到我的mailInformations类? – JEMI 2013-04-30 13:59:39

+0

@JEMI这里是一个例子:http://stackoverflow.com/questions/6312970/restsharp-json-parameter-posting – 2013-04-30 14:38:53

+0

@JEMI你也可以直接发布对象,如果你想要的话:http://stackoverflow.com/questions/ 9966521/restsharp-后对象对WCF – 2013-04-30 14:58:13

相关问题