【问题标题】:How to call Rest ful webservice using httpWebRequest and PostData如何使用 httpWebRequest 和 Post Data 调用 Restful Web 服务
【发布时间】:2013-04-30 12:22:23
【问题描述】:

我已经创建了一个如下所示的宁静的网络服务

运营合同

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/PushNotification")]
        [OperationContract]
        void PushNotification(MailInformation 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 调用此服务?

我的服务网址

localhost/Chat/ChatService.svc/PushNotification

【问题讨论】:

  • 这是一项休息服务。我认为休息服务不代理

标签: .net wcf rest


【解决方案1】:
MailInformation mi = new MailInformation(){
    SenderEmail = "aaa@bbb.com",
    Subject = "test",
    To = new List<string>(){"ccc@eee.com"}
};

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

【讨论】:

  • JsonConvert 类在哪个命名空间中?
  • 对不起..我用Json.net但你也可以用JavaScriptSerializer
  • 但是在服务中mailInformations是空的..我怎样才能得到这个参数?
  • @JEMI 尝试使用WebMessageBodyStyle.Bare 而不是WebMessageBodyStyle.Wrapped
【解决方案2】:

您可以省去使用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

【讨论】:

猜你喜欢
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 2011-08-28
  • 2014-03-14
相关资源
最近更新 更多