C# 后端模式调用接口的几种方法

 public class HttpRequestDemo
    {

        /// 
        /// 请求方式 post 提交 json格式
        /// 对应的服务端接口接收 Task Login(model m)
        /// 
        public void JsonFormatRequest()
        {
            //参数对象
            var data = new
            {
                platform = 1,
                userName = "xxxxxx",
                password = "xxxxxx"
            };
            //将对象参数序列化成json字符串 ,也可以自己手动拼接
            var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            byte[] bs = Encoding.Default.GetBytes(jsonStr);


            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"http://xxx.com/Api/User/Login");//接口地址
            req.Method = "POST"; //请求类型
            req.ContentType = "application/json";
            req.ContentLength = bs.Length;

            //获得请求流
            using (Stream reqStream = req.GetRequestStream())
            {
                //参数写入请求流
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
                //从返回结果流中读取返回数据
                StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.UTF8);
                string result = sr.ReadToEnd();
                Console.WriteLine(result);//打印返回信息 结果可用Newtonsoft.Json.JsonConvert.DeserializeObject 序列化成自己想要的对象
            }

        }


        /// 
        /// 请求方式 Post 提交 body 如 &name=123&xxx  方式传参
        /// 对应的服务端接收参数 Task Login([FromForm]model m)
        /// 
        public void QueryBodyRequest()
        {
            //拼接的即将传入的参数对象
            var queryStr = "&phone=xxxxx&key=xxxxxx&password=xxxx&type=2";
            byte[] bs = Encoding.Default.GetBytes(queryStr);


            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"http://xxx.com/account/login");//接口地址
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded"; 
            req.ContentLength = bs.Length;

            //请求数据
            using (Stream reqStream = req.GetRequestStream())
            {
                //写入流数据
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
                //从返回结果流中读取数据
                StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.UTF8);
                string result = sr.ReadToEnd();
                Console.WriteLine(result);//打印返回信息 结果可用Newtonsoft.Json.JsonConvert.DeserializeObject 序列化成自己想要的对象
            }
        }


        /// 
        /// 请求方式 Post 提交 Body 方式2 效果同上方法 底层也是 &name=123&xxx 方式传参
        /// 对应的服务端接收参数 Task Login([FromBody]model m)
        /// 
        public void BodyFormatRequest()
        {
            try
            {
                HttpClient myHttpClient = new HttpClient();
                var url = "http://www.xxxxx.com/account/login";
                var content = new FormUrlEncodedContent(new Dictionary() {
                      {"phone","18888888"},
                      {"key","CF6D9D9766665367700F9249AD080E9FF9D9" },
                      {"password","123123" },
                      {"type","2" },
                  });

                HttpResponseMessage response = myHttpClient.PostAsync(url, content).Result;
                var result = response.Content.ReadAsByteArrayAsync().Result;
                Console.WriteLine(Encoding.UTF8.GetString(result));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

更多方式后续记录

你可能感兴趣的:(C# 后端模式调用接口的几种方法)