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-reported under the .net core framework. Here we will briefly introduce how to make http requests under .net core. The main ones are still GET and POST methods. If there are any errors, please feel free to correct them!
Let’s talk about POST first. I implemented three methods of POST. The first two principles are completely consistent. There are some slight differences in the latter, but their essence is http request, which is essentially no difference, but the implementation methods are different.
Without further ado, please enter the code:
POST asynchronous method:
/// <summary> /// Asynchronous request post (key value pair form, waiting) /// </summary> /// <param name="uri">Network base address("http://localhost:59315")</param> /// <param name="url">Network address ("/api/UMeng")</param> /// <param name="formData">KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();(new KeyValuePair<string, string>("userid", "29122"));(new KeyValuePair<string, string>("umengids", "29122"));</param> /// <param name="charset">Encoding format</param> /// <param name="mediaType">Head media type</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(); = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); = new MediaTypeHeaderValue(mediaType); = charset; for (int i = 0; i < ; i++) { (formData[i].Key, formData[i].Value); } HttpResponseMessage resp = await (tokenUri, content); (); string token = await (); return token; }
POST synchronization method:
/// <summary> /// Synchronous request post (key value pair form) /// </summary> /// <param name="uri">Network base address("http://localhost:59315")</param> /// <param name="url">Network address ("/api/UMeng")</param> /// <param name="formData">KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();(new KeyValuePair<string, string>("userid", "29122"));(new KeyValuePair<string, string>("umengids", "29122"));</param> /// <param name="charset">Encoding format</param> /// <param name="mediaType">Head media type</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(); = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); = new MediaTypeHeaderValue(mediaType); = charset; for (int i = 0; i < ; i++) { (formData[i].Key, formData[i].Value); } var res = (tokenUri, content); (); HttpResponseMessage resp = ; var res2 = (); (); string token = ; return token; }
Unfortunately, the synchronization method is also implemented asynchronously. I personally think that doing so will increase system overhead. If you have other efficient implementations, please give me some advice!
Next is POST through streaming:
public string Post(string url, string data, Encoding encoding, int type) { try { HttpWebRequest req = (new Uri(url)); if (type == 1) { = "application/json;charset=utf-8"; } else if (type == 2) { = "application/xml;charset=utf-8"; } else { = "application/x-www-form-urlencoded;charset=utf-8"; } = "POST"; // = "text/xml,text/javascript"; = 60000; byte[] postData = (data); Stream reqStream = ().Result; (postData, 0, ); (); var rsp = (HttpWebResponse)().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 { // Read HTTP response in a character stream stream = (); reader = new StreamReader(stream, encoding); return (); } finally { // Free up resources if (reader != null) (); if (stream != null) (); if (rsp != null) (); } }
In this way, POST is still to write data into the stream and perform POST. The reason why the first two key-value forms are written 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 webapi), I will talk about how to receive (key-value) forms in webapi to appropriately avoid the conflict between .net background personnel and Android and iOS.
Next is get, and synchronous asynchronous is implemented by asynchronously. Please give me a quick comment.
GET:
/// <summary> /// Asynchronous request get(UTF-8) /// </summary> /// <param name="url">link address</param> /// <param name="formData">Content written in the 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) { = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); = "UTF-8"; for (int i = 0; i < ; i++) { (formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = , }; for (int i = 0; i < ; i++) { (formData[i].Key, formData[i].Value); } var resp = await (request); (); string token = await (); return token; }
/// <summary> /// Synchronize get requests /// </summary> /// <param name="url">link address</param> /// <param name="formData">Key-value pairs written in header</param> /// <returns></returns> public string HttpGet(string url, List<KeyValuePair<string, string>> formData = null) { HttpClient httpClient = new HttpClient(); HttpContent content = new FormUrlEncodedContent(formData); if (formData != null) { = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); = "UTF-8"; for (int i = 0; i < ; i++) { (formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = , }; for (int i = 0; i < ; i++) { (formData[i].Key, formData[i].Value); } var res = (request); (); var resp = ; Task<string> temp = (); (); return ; }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.