如何使用POST 方法调用服务
一、WCF REST专用POST方法
1.1、 建立WCF REST 方法
[ServiceContract] public interface IBookingBizService { [WebInvoke(UriTemplate = "setdeliver", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract()] OperateResult SetDeliver(string args); }
1.2、 POST调用WCF REST 方法
private string UseHttpWebApproach(string serviceUrl, string resourceUrl, string method, string requestBody) { string responseMessage = null; var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest; if (request != null) { request.ContentType = "application/json"; request.Method = method; } if (method == "POST" && requestBody != null) { byte[] requestBodyBytes = ToByteArrayUsingJsonContractSer(requestBody); request.ContentLength = requestBodyBytes.Length; using (Stream postStream = request.GetRequestStream()) postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length); } if (request != null) { var response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { Stream responseStream = response.GetResponseStream(); if (responseStream != null) { var reader = new StreamReader(responseStream); responseMessage = reader.ReadToEnd(); } } else { responseMessage = response.StatusDescription; } } return responseMessage; } private static byte[] ToByteArrayUsingJsonContractSer(string requestBody) { byte[] bytes = null; var serializer1 = new DataContractJsonSerializer(typeof(string)); var ms1 = new MemoryStream(); serializer1.WriteObject(ms1, requestBody); ms1.Position = 0; var reader = new StreamReader(ms1); bytes = ms1.ToArray(); return bytes; }
调用WCF REST 方法和一般的POST方法有所不同,区别在于发送前对数据的编码,采用DataContractJsonSerializer 进行序列化。
一般的对POST方法的调用采用如何数据编码
private static byte[] ToByteArray(string requestBody) { byte[] bytes = null; bytes = Encoding.UTF8.GetBytes(requestBody); return bytes; }
如果要建立通用的POST调用服务,不建议采用WCF REST 形式,如果只是针对.net 平台的调用到时没有关系。