Post方式调用wcf服务
我们寻常在PC端调用WCF服务,仅仅要知道WCF服务的地址。client直接加入引用服务就能够使用了,殊不知还有其它方式,事实上。我们也能够
通过HTTP POST的方式调用WCF服务。这样就不用加入引用了。在手机移动端开发后台服务,都是通过Post的形式调用WCF服务,当然。这样的方式在PC也能够使用。
我们来看以下的一个简单演示样例。
以下的演示样例演示了server端和client的简单通讯
server端返回一个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);
}
client调用
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 "无法连接到server\r\n错误信息:" + ex.Message;
}
}
string param = "appKey=44hbf622op&username=13011001233&sign=123456";
postSend("http://localhost:17446/CusDataService.svc/AddData", param);
浙公网安备 33010602011771号