Asp.net core uses HttpClient to implement synchronous asynchronous Post and Get methods. corehttpclient

Source: Internet
Author: User
Tags webp

Asp.net core uses HttpClient to implement synchronous asynchronous Post and Get methods. corehttpclient

Preparations

1. visual studio 2015 update3 Development Environment

2. net core 1.0.1 and later versions

Directory

1. HttpGet Method

2. HttpPost Method

3. Example

4. Download Code

1 HttpGet

 

/// <Summary> /// use the Get method to obtain the string result (no Cookie is added) /// </summary> /// <param name = "url"> </param> /// <returns> </returns> public static async Task <string> HttpGetAsync (string url, encoding encoding = null) {HttpClient httpClient = new HttpClient (); var data = await httpClient. getByteArrayAsync (url); var ret = encoding. getString (data); return ret ;} /// <summary> /// Http Get synchronization method /// </summary> /// <param name = "url"> </param> /// <param name = "encoding"> </param> // <returns> </returns> public static string HttpGet (string url, encoding encoding = null) {HttpClient httpClient = new HttpClient (); var t = httpClient. getByteArrayAsync (url); t. wait (); var ret = encoding. getString (t. result); return ret ;}

  

2 HttpPost Method

/// <Summary> /// POST asynchronous // </summary> /// <param name = "url"> </param> /// <param name = "postStream"> </param> // <param name = "encoding"> </param> // <param name = "timeOut"> </param> // /<returns> </returns> public static async Task <string> HttpPostAsync (string url, dictionary <string, string> formData = null, Encoding encoding = null, int timeOut = 10000) {HttpClientHandler handler = new HttpClientH Andler (); HttpClient client = new HttpClient (handler); MemoryStream MS = new MemoryStream (); formData. fillFormDataStream (MS); // fill formData HttpContent hc = new StreamContent (MS); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("text/html"); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("application/xhtml + xml"); client. defaultRequestHeaders. Accept. add (new MediaTypeWithQualityHeaderValue ("application/xml", 0.9); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("image/webp"); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("*/*", 0.8); hc. headers. add ("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); hc. Headers. add ("Timeout", timeOut. toString (); hc. headers. add ("KeepAlive", "true"); var r = await client. postAsync (url, hc); byte [] tmp = await r. content. readAsByteArrayAsync (); return encoding. getString (tmp );} /// <summary> /// POST synchronization // </summary> /// <param name = "url"> </param> /// <param name = "postStream"> </param> // <param name = "encoding"> </param> // <param name = "timeOut"> </param> // /<retur Ns> </returns> public static string HttpPost (string url, Dictionary <string, string> formData = null, Encoding encoding = null, int timeOut = 10000) {HttpClientHandler handler = new HttpClientHandler (); HttpClient client = new HttpClient (handler); MemoryStream MS = new MemoryStream (); formData. fillFormDataStream (MS); // fill formData HttpContent hc = new StreamContent (MS); client. defaultRequestHeaders. A Ccept. add (new MediaTypeWithQualityHeaderValue ("text/html"); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("application/xhtml + xml"); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("application/xml", 0.9); client. defaultRequestHeaders. accept. add (new MediaTypeWithQualityHeaderValue ("image/webp"); client. defaultRequestHeaders. accept. add (ne W MediaTypeWithQualityHeaderValue ("*/*", 0.8); hc. headers. add ("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); hc. headers. add ("Timeout", timeOut. toString (); hc. headers. add ("KeepAlive", "true"); var t = client. postAsync (url, hc); t. wait (); var t2 = t. result. content. readAsByteArrayAsync (); return encoding. getString (t2.Res Ult) ;}/// <summary> /// the method used to assemble QueryString is connected with &, and there is no symbol in the first place, for example: a = 1 & B = 2 & c = 3 // </summary> /// <param name = "formData"> </param> /// <returns> </returns> public static string GetQueryString (this Dictionary <string, string> formData) {if (formData = null | formData. count = 0) {return "";} StringBuilder sb = new StringBuilder (); var I = 0; foreach (var kv in formData) {I ++; sb. appendFormat ("{0} = {1} ", kv. key, kv. value); if (I <formData. count) {sb. append ("&") ;}} return sb. toString ();} /// <summary> /// Stream that fills the form information /// </summary> /// <param name = "formData"> </param> // <param name = "stream"> </param> public static void FillFormDataStream (this Dictionary <string, string> formData, Stream stream) {string dataString = GetQueryString (formData); var formDataBytes = formData = null? New byte [0]: Encoding. UTF8.GetBytes (dataString); stream. write (formDataBytes, 0, formDataBytes. length); stream. seek (0, SeekOrigin. begin); // set the pointer reading position}

  

 

3 Examples

Modify the index. cshtml file under View

@{    ViewData["Title"] = "Home Page";    Layout = null;} @{   @*var ret1=await httpclientdemo.HttpHelper.HttpGetAsync("http://www.baidu.com", System.Text.Encoding.GetEncoding("utf-8"));    @Html.Raw(ret1)*@    @*var ret2 = httpclientdemo.HttpHelper.HttpGet("http://www.baidu.com", System.Text.Encoding.GetEncoding("utf-8"));    @Html.Raw(ret2)*@    var ret3 = httpclientdemo.HttpHelper.HttpPost("http://www.baidu.com",null, System.Text.Encoding.GetEncoding("utf-8"));    @Html.Raw(ret3)    @*var ret4 = await httpclientdemo.HttpHelper.HttpPostAsync("http://www.baidu.com", null, System.Text.Encoding.GetEncoding("utf-8"),10000);    @Html.Raw(ret4)*@}

 

4. Download Code

Link: http://pan.baidu.com/s/1gfdqwDX password: dxzp

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.