Specific information about instance code sharing for network requests under C #. NET Core

Source: Internet
Author: User
This article focuses on a detailed description of the network request under C #. NET core, and outlines how to make HTTP requests under. NET core, mostly still the get and post methods, which are interesting to understand

This article is in the VS2017 environment, the. NET core 1.1 version above.

During this time, because. NET core is not based on IIS, our past network request code under the. NET Core framework, there may be incompatibilities, error symptoms. Here is a general description of how to make HTTP requests under the. NET core, mostly still get and post methods, where there are errors, please correct me!

First of all, Post,post. I implemented three methods, the first two based on the principle is exactly the same, behind some small differences, but their essence is the HTTP request, essentially no difference, but the implementation method is different.

Nonsense not much to say, on the code:

Post Async Method:

 <summary>////Asynchronous request post (key-value pair form, can wait)///</summary>//<param name= "uri" > Network base Address ("Http://local host:59315 ") </param>//<param name=" url "> Address of the Network ("/api/umeng ") </param>//<param name=" Formdat A "> 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>//<p Aram Name= "mediatype" > Head Media Type </param>//<returns></returns> public async task<string> Htt Ppostasync (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>///sync request post (key-value pair form)///</summary>//<param name= "uri" > Network base Address ("Http://localhost:5 9315 ") </param>//<param name=" url "> Address of the Network ("/api/umeng ") </param>//<param name=" FormData "> Key value pairs 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 Nam E= "mediatype" > Head Media Type </param>//<returns></returns> public string HttpPost (string uri, String u RL, list<keyvaluepair<string, string>> formData = null, String charset = "UTF-8", String mediatype = "Applicat      Ion/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 approach is also based on asynchronous implementations, which the individual believes will increase the overhead of the system. If you have other efficient implementation, please do not hesitate to enlighten!

The next step is to post via a 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 a character stream        . GetResponseStream ();        reader = new StreamReader (stream, encoding);        Return reader. ReadToEnd ();      }      Finally      {        //Frees Resource        if (reader! = null) reader. Dispose ();        if (stream! = null) stream. Dispose ();        if (RSP! = NULL) RSP. Dispose ();      }    }

This way of post or write data into the stream, post, the reason for writing the first two key-value form, is to conform to the Java or OC style, in C # written in the Webapi, because the receiving form is {=value} instead of {Key=value} ( Determined by the nature of Webapi), follow-up I will say how to receive (Key-value) in the form of WEBAPI, appropriate to avoid. NET background personnel and Android and iOS contradictions, so as to achieve the stability of socialist democratic society.

Next is get, the same synchronous asynchronous is implemented asynchronously, also please crossing light spray.

GET:

 <summary>////Asynchronous request get (UTF-8)///</summary>//<param name= "url" > link address </param> <param name= "FormData" > What to write in the header </param>//<returns></returns> public static Asyn C task<string> httpgetasync (string url, list<keyvaluepair<string, string>> formData = null) {Ht      Tpclient 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.G      ET,}; 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>///Sync GET request///</summary>//<param name= "url" > Link address </param>/// Lt;param name= "FormData" > Write a key value pair in the header </param>//<returns></returns> public string HttpGet (St Ring 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.G      ET,}; 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; }
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.