关于C# 怎么调用webapi来获取到json数据

 1        /// <summary>
 2        /// 调用api返回json
 3        /// </summary>
 4        /// <param name="url">api地址</param>
 5        /// <param name="jsonstr">接收参数</param>
 6        /// <param name="type">类型</param>
 7        /// <returns></returns>
 8        public static string HttpApi(string url, string jsonstr, string type)
 9        {
10            Encoding encoding = Encoding.UTF8;
11            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
12            request.Accept = "text/html,application/xhtml+xml,*/*";
13            request.ContentType = "application/json";
14            request.Method = type.ToUpper().ToString();//get或者post
15            byte[] buffer = encoding.GetBytes(jsonstr);
16            request.ContentLength = buffer.Length;
17            request.GetRequestStream().Write(buffer, 0, buffer.Length);
18            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
19            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
20            {
21                return reader.ReadToEnd();
22            }
23        }

 

posted @ 2018-09-23 22:56  杨浪  阅读(1616)  评论(0编辑  收藏  举报