C# 調用webapi


C#winform程序調用webapi:

/// <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, 0, buffer.Length);
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
           using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
           {
               return reader.ReadToEnd();
           }
       }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM