C#Post時Body序列化

時間:2020-09-07

背景:調用別人的POST的接口 

協議:http

開發工具:VS2019 

調試工具:Postman,Swagger

 

Postman是一款比較好用的接口測試工具,在調用別人接口前,可先測試接口是否OK

使用POST請求的方法

 

		/// 
        /// 調用的例子
        /// 
        /// 2020-08-01
        /// MFGII
        /// 
        private string GetPCAS(string month, string bu)
        {
            //序列化
            string postBody = JsonConvert.SerializeObject(new
            {
                username = "id",
                by = "days",
                month = month,
                @for = bu
			});
			//Second為一個實體類,我是按照接口得到的數據自己建的
			var data = JsonHelper.Deserialize(HttpPost(url, postBody) );   
		}

將接收到的json字符串反序列化

  public static T Deserialize(string json)
        {
            T obj = Activator.CreateInstance();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }

調用POST請求的方法

        /// 
        /// 发起POST请求
        /// 
        /// 
        /// 
        /// application/xml、application/json、application/text、application/x-www-form-urlencoded
        /// 单位 秒
        /// 填充消息头        
        /// 
        public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 120, Dictionary headers = null)
        {
            postData = postData ?? "";
            ServicePointManager.DefaultConnectionLimit = 512;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = contentType;
            request.Timeout = timeOut * 1000;
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers.Add(header.Key, header.Value);
            }
            request.Method = "POST";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (var httpStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return httpStreamReader.ReadToEnd();
            }
        }

 

你可能感兴趣的:(C#)