C# 调用api 并解析返回的json字符串

C# 调用api 并 解析返回的json字符串

1. 调用api

  1. 首先需要引用 using System.IO; using System.Net;
  2. 编写请求api函数,下面是发送 GET 请求函数。
        //请求api
        public static string ApiGet(string url)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
  1. 发送POST请求的函数。
        public static string ApiPost(string url, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
  1. 以GET方式,请求api。如果需要传值,在url中添加即可。
    例如:发送请求携带传用户名和密码 :“http://127.0.0.1:8000/detail/test?userName=123&password=123”
        static void Main(string[] args)
        {
            string jsonStr = ApiGet("http://127.0.0.1:8000/detail/test");
        }
  1. 以POST方式,请求api。携带json格式的用户名和密码。
        static void Main(string[] args)
        {
            string jsonStr = ApiPost("http://127.0.0.1:8000/detail/test", "{userName:\"123\",password:\"123\"}");
        }

2. 解析json字符串

  1. 首先需要在解决方案中.右击 引用 添加引用,选择 System.Web.Extensions,确定。

C# 调用api 并解析返回的json字符串_第1张图片

  1. 引用命名空间 using System.Web.Script.Serialization;
  2. 编写接收的Json串的属性。例如接收的Json串是{“code”: 200,“message”:“get”},需要为键创建属性。
        public class Test
        {
            public int code { get; set; }
            public string message { get; set; }
        }
  1. 解析Json串。
        static void Main(string[] args)
        {
            //请求api
            string jsonStr = ApiGet("http://127.0.0.1:8000/detail/test");
            
            //解析Json串
            JavaScriptSerializer js = new JavaScriptSerializer();
            var model = js.Deserialize<Test>(jsonStr);

            //输出值
            Console.WriteLine(model.code);
            Console.WriteLine(model.message);
        }

控制台:C# 调用api 并解析返回的json字符串_第2张图片

你可能感兴趣的:(C#,c#,json,api,get,post)