Home >Backend Development >C#.Net Tutorial >Detailed introduction to the example code sharing of network requests under C# .net core
This article mainly introduces the detailed explanationc# Network requests under .net core. It briefly introduces how to make http requests under .net core. The main methods are still GET and POST. If you are interested, you can Understand
This article is in the VS2017 environment, .net core version 1.1 or above.
During this period, since .net core is not based on IIS, our past network request code may be incompatible and error reporting under the .net coreframework. Here is a general introduction on how to make http requests under .net core. The main methods are still GET and POST. If there are any errors, please correct me!
Let’s talk about POST first. I have implemented three methods for POST. The first two are based on the same principles. There are some small differences in the latter ones, but their essence is http request. In essence, There is no difference, just the implementation method is different.
Without further ado, here’s the code:
POST asynchronous method:
/// <summary> /// 异步请求post(键值对形式,可等待的) /// </summary> /// <param name="uri">网络基址("http://localhost:59315")</param> /// <param name="url">网络的地址("/api/UMeng")</param> /// <param name="formData">键值对List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param> /// <param name="charset">编码格式</param> /// <param name="mediaType">头媒体类型</param> /// <returns></returns> public async Task<string> HttpPostAsync(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded") { string tokenUri = url; var client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); content.Headers.ContentType.CharSet = charset; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } HttpResponseMessage resp = await client.PostAsync(tokenUri, content); resp.EnsureSuccessStatusCode(); string token = await resp.Content.ReadAsStringAsync(); return token; }
POST synchronous method:
/// <summary> /// 同步请求post(键值对形式) /// </summary> /// <param name="uri">网络基址("http://localhost:59315")</param> /// <param name="url">网络的地址("/api/UMeng")</param> /// <param name="formData">键值对List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param> /// <param name="charset">编码格式</param> /// <param name="mediaType">头媒体类型</param> /// <returns></returns> public string HttpPost(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded") { string tokenUri = url; var client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); content.Headers.ContentType.CharSet = charset; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } var res = client.PostAsync(tokenUri, content); res.Wait(); HttpResponseMessage resp = res.Result; var res2 = resp.Content.ReadAsStringAsync(); res2.Wait(); string token = res2.Result; return token; }
Unfortunately, the synchronous method is also based on asynchronous implementation. I personally think that doing so will increase system overhead. If you have other efficient implementations, please feel free to let me know!
The next step is to perform POST through the stream:
public string Post(string url, string data, Encoding encoding, int type) { try { HttpWebRequest req = WebRequest.CreateHttp(new Uri(url)); if (type == 1) { req.ContentType = "application/json;charset=utf-8"; } else if (type == 2) { req.ContentType = "application/xml;charset=utf-8"; } else { req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; } req.Method = "POST"; //req.Accept = "text/xml,text/javascript"; req.ContinueTimeout = 60000; byte[] postData = encoding.GetBytes(data); Stream reqStream = req.GetRequestStreamAsync().Result; reqStream.Write(postData, 0, postData.Length); reqStream.Dispose(); var rsp = (HttpWebResponse)req.GetResponseAsync().Result; var result = GetResponseAsString(rsp, encoding); return result; } catch (Exception ex) { throw; } }
private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Dispose(); if (stream != null) stream.Dispose(); if (rsp != null) rsp.Dispose(); } }
This method of POST still writes the data into the stream and performs POST. The reason why the first two key-values are written is The form is to conform to the style of Java or OC. In the webapi written in C#, since the receiving form is {=value} instead of {key=value} (determined by the nature of the webapi), I will talk about how to receive it in the webapi later. (key-value) form, appropriately avoid conflicts between .net backend personnel and android and ios, thereby achieving long-term stability in a socialist democratic society.
Next is get. Similarly, synchronous and asynchronous are all implemented by asynchronous, please read it lightly.
GET:
/// <summary> /// 异步请求get(UTF-8) /// </summary> /// <param name="url">链接地址</param> /// <param name="formData">写在header中的内容</param> /// <returns></returns> public static async Task<string> HttpGetAsync(string url, List<KeyValuePair<string, string>> formData = null) { HttpClient httpClient = new HttpClient(); HttpContent content = new FormUrlEncodedContent(formData); if (formData != null) { content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.ContentType.CharSet = "UTF-8"; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = HttpMethod.Get, }; for (int i = 0; i < formData.Count; i++) { request.Headers.Add(formData[i].Key, formData[i].Value); } var resp = await httpClient.SendAsync(request); resp.EnsureSuccessStatusCode(); string token = await resp.Content.ReadAsStringAsync(); return token; }rrree
The above is the detailed content of Detailed introduction to the example code sharing of network requests under C# .net core. For more information, please follow other related articles on the PHP Chinese website!