接口的调用和返回值的处理(Post请求)

首先是post请求的调用,调用对方的接口首先要得到对方的url,和需要传入的参数,下面是一个简单的post请求

            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json");
            Encoding enc = Encoding.GetEncoding("UTF-8");
            //通过json的方式传递数据
            var datajson = new JavaScriptSerializer().Serialize(
                new
                {
                    serviceId = "3c.park.queryparkplacelist",
                    requestType = "DATA",
                    attributes = new
                    {
                        parkCode = "g3v3_1",
                        placeType = "SALE",
                        areaName = "A区",
                        floor = "2",
                        status = 1,
                        pageSize = 10,
                        pageIndex = 1

                    }
                });

            //调用post方法进行请求,用result来接收返回的数据
            var result = Post(URL, datajson);                    

下面是请求的具体方法

  /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json_param">参数</param>
        /// <param name="sign">md5加密</param>
        /// <returns></returns>
        public static string Post(string url, string json_param, string sign = "")
        {
            int timeoutSeconds = 0;
            WebProxy proxy = null;
            string contentType = "application/json;charset=UTF-8";

            Encoding encoding = Encoding.GetEncoding("UTF-8");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (proxy != null) request.Proxy = proxy;
            if (timeoutSeconds > 0)
            {
                request.Timeout = 0x3e8 * timeoutSeconds;
            }
            if (sign != "")
            {
                request.Headers["sign"] = sign;
            }
            request.Method = "POST";
            request.AllowAutoRedirect = true;
            request.ContentType = contentType;
            request.ServicePoint.Expect100Continue = false;

            byte[] bytes = encoding.GetBytes(json_param);
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
            return reader.ReadToEnd();
        }

之后我们可以将接收到的数据进行解析,解析有多种方式,下面以json字符串的格式为例

//首先要创建此实例
JavaScriptSerializer js = new JavaScriptSerializer();
//然后通过此方法解析出返回的实体类 ——需要事先创建好实体类来进行接收,具体的参数根据返回值确定无需进行其他操作
OutParkModel Model = js.Deserialize<OutParkModel>(postContent);

 

上一篇:j


下一篇:python --微信v3支付