Explain the network requests under c #. net core,

Source: Internet
Author: User

Explain the network requests under c #. net core,

This article is about. net core 1.1 or later in the VS2017 environment.

During this period, because. net core is not based on IIS, our previous network Request Code may be incompatible and report errors under the. net core framework. Here we will give a general introduction to How to Make http requests under. net core, mainly the GET and POST methods. If there are any errors, please let me know!

First, POST and POST are implemented in three ways. The first two principles are completely consistent. There are some minor differences in the latter, but they are essentially http requests, essentially, there is no difference, but the implementation methods are different.

Not much nonsense. Go to 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"> key-Value Pair 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"> encoding format </param> /// <param name = "mediaType"> header 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 (); 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 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"> key-Value Pair 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"> encoding format </param> /// <param name = "mediaType"> header 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 (); 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 implemented based on Asynchronization. I personally think this will increase the system overhead. If you have other efficient implementations, please do not hesitate to give me some advice!

The next step is to 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 {// read HTTP Response stream = rsp in response Stream mode. getResponseStream (); reader = new StreamReader (stream, encoding); return reader. readToEnd ();} finally {// release the resource if (reader! = Null) reader. Dispose (); if (stream! = Null) stream. Dispose (); if (rsp! = Null) rsp. Dispose ();}}

This method of POST writes data to the stream for POST. The reason why the first two key-value formats are written is to conform to the java or oc style, in the webapi written in c #, because the receipt form is {= value} rather than {key = value} (determined by the nature of webapi ), in the future, I will explain how to receive (key-value) form in webapi and avoid it as appropriate. net background staff conflicts with android and ios to achieve long-term stability in a socialist democratic society.

The next step is get. synchronous Asynchronization is also implemented asynchronously. Please take a look at it.

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) {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 ;}
/// <Summary> /// synchronize get requests /// </summary> /// <param name = "url"> link address </param> /// <param name = "formData"> key-value pairs written in the 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) {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 res = httpClient. sendAsync (request); res. wait (); var resp = res. result; Task <string> temp = resp. content. readAsStringAsync (); temp. wait (); return temp. result ;}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.