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

时间:2023-02-20 09:06:50
        /// <summary>
       /// 调用api返回json
       /// </summary>
       /// <param name="url">api地址</param>
       /// <param name="jsonstr">接收参数</param>
       /// <param name="type">类型</param>
       /// <returns></returns>
       public static string HttpApi(string url, string jsonstr, string type)
       {
           Encoding encoding = Encoding.UTF8;
           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
           request.Accept = "text/html,application/xhtml+xml,*/*";
           request.ContentType = "application/json";
           request.Method = type.ToUpper().ToString();//get或者post
           byte[] buffer = encoding.GetBytes(jsonstr);
           request.ContentLength = buffer.Length;
           request.GetRequestStream().Write(buffer, , buffer.Length);
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
           using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
           {
               return reader.ReadToEnd();
           }
       }