如何使用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 平台的調用到時沒有關系。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM