Post方式调用wcf服务
2017-10-16 20:47 sunice 阅读(2780) 评论(0) 编辑 收藏 举报我们平常在PC端调用WCF服务,只要知道WCF服务的地址,客户端直接添加引用服务就可以使用了,殊不知还有其他方式,其实,我们也可以
通过HTTP POST的方式调用WCF服务,这样就不用添加引用了,在手机移动端开发后台服务,都是通过Post的形式调用WCF服务,当然,这种方式在PC也可以使用。
我们来看下面的一个简单示例。下面的示例演示了服务器端和客户端的简单通讯
服务器端返回一个JSON字符串,代码如下
契约定义
1 [OperationContract] 2 [WebInvoke(UriTemplate = "AddData", Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] 3 string AddData(Stream stream);
契约实现
1 public string AddData(Stream stream) 2 { 3 StreamReader sr = new StreamReader(stream); 4 string s = sr.ReadToEnd(); 5 sr.Dispose(); 6 NameValueCollection nvc = HttpUtility.ParseQueryString(s); 7 8 string appKey = nvc["appKey"]; 9 string sign = nvc["sign"]; 10 string name=nvc["username"]; 11 12 var result = new ErrorModel 13 { 14 IsError = true, 15 ErrorCode = -2, 16 ErrorMsg = "操作信息", 17 }; 18 return new JavaScriptSerializer().Serialize(result); 19 }
客户端调用
1 public static string postSend(string url, string param) 2 { 3 Encoding myEncode = Encoding.GetEncoding("UTF-8"); 4 byte[] postBytes = Encoding.UTF8.GetBytes(param); 5 6 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); 7 req.Method = "POST"; 8 req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; 9 req.ContentLength = postBytes.Length; 10 11 try 12 { 13 using (Stream reqStream = req.GetRequestStream()) 14 { 15 reqStream.Write(postBytes, 0, postBytes.Length); 16 } 17 using (WebResponse res = req.GetResponse()) 18 { 19 using (StreamReader sr = new StreamReader(res.GetResponseStream(), myEncode)) 20 { 21 string strResult = sr.ReadToEnd(); 22 return strResult; 23 } 24 } 25 } 26 catch (WebException ex) 27 { 28 return "无法连接到服务器\r\n错误信息:" + ex.Message; 29 } 30 }
1 string param = "appKey=44hbf622op&username=13011001233&sign=123456"; 2 3 postSend("http://localhost:17446/CusDataService.svc/AddData", param);
1 <services> 2 <service behaviorConfiguration="RESTBehaviour" name="Jawasoft.TrackCodeService.Server.TrackCodeService"> 3 <endpoint address="" behaviorConfiguration="webHttp" binding="webHttpBinding" 4 ame="post" contract="Jawasoft.TrackCodeService.Server.ITrackCodeService"/> 5 6 </service> 7 </services>
转载:
http://blog.csdn.net/zx13525079024/article/details/27069379