我们平常在PC端调用WCF服务,只要知道WCF服务的地址,客户端直接添加引用服务就可以使用了,殊不知还有其他方式,其实,我们也可以
通过HTTP POST的方式调用WCF服务,这样就不用添加引用了,在手机移动端开发后台服务,都是通过Post的形式调用WCF服务,当然,这种方式在PC也可以使用。
我们来看下面的一个简单示例。下面的示例演示了服务器端和客户端的简单通讯
服务器端返回一个JSON字符串,代码如下
契约定义
- [OperationContract]
- [WebInvoke(UriTemplate = "AddData", Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
- string AddData(Stream stream);
契约实现
- public string AddData(Stream stream)
- {
- StreamReader sr = new StreamReader(stream);
- string s = sr.ReadToEnd();
- sr.Dispose();
- NameValueCollection nvc = HttpUtility.ParseQueryString(s);
- string appKey = nvc["appKey"];
- string sign = nvc["sign"];
- string name=nvc["username"];
- var result = new ErrorModel
- {
- IsError = true,
- ErrorCode = -2,
- ErrorMsg = "操作信息",
- };
- return new JavaScriptSerializer().Serialize(result);
- }
客户端调用
- public static string postSend(string url, string param)
- {
- Encoding myEncode = Encoding.GetEncoding("UTF-8");
- byte[] postBytes = Encoding.UTF8.GetBytes(param);
- HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
- req.Method = "POST";
- req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
- req.ContentLength = postBytes.Length;
- try
- {
- using (Stream reqStream = req.GetRequestStream())
- {
- reqStream.Write(postBytes, 0, postBytes.Length);
- }
- using (WebResponse res = req.GetResponse())
- {
- using (StreamReader sr = new StreamReader(res.GetResponseStream(), myEncode))
- {
- string strResult = sr.ReadToEnd();
- return strResult;
- }
- }
- }
- catch (WebException ex)
- {
- return "无法连接到服务器\r\n错误信息:" + ex.Message;
- }
- }
- string param = "appKey=44hbf622op&username=13011001233&sign=123456";
- postSend("http://localhost:17446/CusDataService.svc/AddData", param);