WebClient调用远程接口

        ///
        /// 调用接口,发送的参数
        ///

   class SendParams
   {
       internal int DeliveryID { get; set; }
          internal int OrderStatusID { get; set; }
       internal String Reason { get; set; }
   }
        ///
        /// 接口返回的结果
        ///

   class ReceiveResult
   {
            internal int code { get; set; }
            internal String msg { get; set; }
            internal String result { get; set; }
   }
        ///
        /// 调用远程接口
        ///

        /// 接口地址
        /// 接口参数
        /// 返回结果对象
        private ReceiveResult CallRemoteInterface(String url,SendParams sendParams)
        {
            string postData = "DeliveryID=" + sendParams.DeliveryID + "&OrderStatusID=" + sendParams.OrderStatusID + "&Reason=" + sendParams.Reason;
            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            client.Headers.Add("ContentLength", postData.Length.ToString());
            String jsonResult = client.UploadData(url, "POST", bytes).ToString();  
            //把返回的json构造成c#对象
            ReceiveResult receiveResult = null;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(receiveResult.GetType());
            using (MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonResult)))
{
                receiveResult = (ReceiveResult)serializer.ReadObject(mStream);
}
            return receiveResult;
        }

你可能感兴趣的:(C#/.Net,Framework/.Net,Core)