介绍 1。WebRequest方式
2。null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
如何在c#项目中调用WebApi ?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
1。WebRequest方式
:
private void button1_Click (object ,发送方,EventArgs e) ,,,,,,,{ ,,,,,,,,,,string 党卫军=,HttpPost (“http://localhost: 41558/api/演示/PostXXX",,“{代码:\“test089 \“,名字:\“test1 \“}”); ,,,,,,,} ,,,,,,,public static string HttpPost (string url, string 身体) ,,,,,,,{ ,,,,,,,,,,,//ServicePointManager.ServerCertificateValidationCallback =, new RemoteCertificateValidationCallback (CheckValidationResult); ,,,,,,,,,,,Encoding Encoding =, Encoding.UTF8; ,,,,,,,,,,,HttpWebRequest request =, (HttpWebRequest) WebRequest.Create (url); ,,,,,,,,,,,request.Method =,“POST"; ,,,,,,,,,,,request.Accept =,“text/html, application/xhtml + xml, */*“; ,,,,,,,,,,,request.ContentType =,“应用程序/json"; ,,,,,, ,,,,,,,,,,,byte [], buffer =, encoding.GetBytes(身体); ,,,,,,,,,,,request.ContentLength =, buffer.Length; ,,,,,,,,,,,request.GetRequestStream () .Write(缓冲,0,buffer.Length); ,,,,,,,,,,,HttpWebResponse response =, (HttpWebResponse) request.GetResponse (); ,,,,,,,,,,,using (StreamReader reader =, new StreamReader (response.GetResponseStream (),, Encoding.UTF8)) ,,,,,,,,,,,{ ,,,,,,,,,,,,,,,return reader.ReadToEnd (); ,,,,,,,,,,,} ,,,,,,,}
:
private void button1_Click (object ,发送方,EventArgs e) ,,,,,,,{ ,,,,,,,,,,,string ss =, HttpGet (“http://localhost: 41558/api/演示/GetXXX ? Name=北京“); ,,,,,,,} ,,,,,,,public static string HttpGet (string url) ,,,,,,,{ ,,,,,,,,,,,//ServicePointManager.ServerCertificateValidationCallback =, new RemoteCertificateValidationCallback (CheckValidationResult); ,,,,,,,,,,,Encoding Encoding =, Encoding.UTF8; ,,,,,,,,,,,HttpWebRequest request =, (HttpWebRequest) WebRequest.Create (url); ,,,,,,,,,,,request.Method =,“GET"; ,,,,,,,,,,,request.Accept =,“text/html, application/xhtml + xml, */*“; ,,,,,,,,,,,request.ContentType =,“应用程序/json"; ,,,,,,,,,, ,,,,,,,,,,,HttpWebResponse response =, (HttpWebResponse) request.GetResponse (); ,,,,,,,,,,,using (StreamReader reader =, new StreamReader (response.GetResponseStream (),, Encoding.UTF8)) ,,,,,,,,,,,{ ,,,,,,,,,,,,,,,return reader.ReadToEnd (); ,,,,,,,,,,,} ,,,,,,,}