网络知识 娱乐 C# 调用Web Api通用方法

C# 调用Web Api通用方法

应粉丝要求写一篇C#调用web api的文章。@globlement

C# 调用WebApi

1.WebRequest方式

Post:

private void button1_Click(object sender, EventArgs e)n {n string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:"test089",Name:"test1"}");n }nn public static string HttpPost(string url, string body)n {n //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);n Encoding encoding = Encoding.UTF8;n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);n request.Method = "POST";n request.Accept = "text/html, application/xhtml+xml, */*";n request.ContentType = "application/json";n n byte[] buffer = encoding.GetBytes(body);n request.ContentLength = buffer.Length;n request.GetRequestStream().Write(buffer, 0, buffer.Length);n HttpWebResponse response = (HttpWebResponse)request.GetResponse();n using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))n {n return reader.ReadToEnd();n }n }

Get:

private void button1_Click(object sender, EventArgs e)n {n string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京");n }nn public static string HttpGet(string url)n {n //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);n Encoding encoding = Encoding.UTF8;n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);n request.Method = "GET";n request.Accept = "text/html, application/xhtml+xml, */*";n request.ContentType = "application/json";n n HttpWebResponse response = (HttpWebResponse)request.GetResponse();n using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))n {n return reader.ReadToEnd();n }n }

2.HttpClient 方式

Post:

private async void button2_Click(object sender, EventArgs e)n{n HttpClient client = new HttpClient();n //由HttpClient发出Delete Methodn HttpResponseMessage response = await client.DeleteAsync("http://localhost:41558/api/Demo"+"/1");n if (response.IsSuccessStatusCode)n MessageBox.Show("成功");n}nnprivate async void button3_Click(object sender, EventArgs e)n{n //创建一个处理序列化的DataContractJsonSerializern DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));n MemoryStream ms = new MemoryStream();n //将资料写入MemoryStreamn serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" });n //一定要在这设定Positionn ms.Position = 0;n HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContentn content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");n HttpClient client = new HttpClient();n //由HttpClient发出Put Methodn HttpResponseMessage response = await client.PutAsync("http://localhost:41558/api/Demo"+ "/1", content);n if (response.IsSuccessStatusCode)n MessageBox.Show("成功");n}

Get:

using (WebClient client = new WebClient())n{n client.Headers["Type"] = "GET";n client.Headers["Accept"] = "application/json";n client.Encoding = Encoding.UTF8;n client.DownloadStringCompleted += (senderobj, es) =>n {n var obj = es.Result;n };n client.DownloadStringAsync("http://localhost:41558/api/Demo");n}