首页 > 代码库 > asp.net core中使用HttpClient实现Post和Get的同步异步方法

asp.net core中使用HttpClient实现Post和Get的同步异步方法

 准备工作

 1.visual studio 2015 update3开发环境

 2.net core 1.0.1 及以上版本

 目录

 1.HttpGet方法

 2.HttpPost方法

 3.使用示例

 4.代码下载

 1 HttpGet

 

 /// <summary>
        /// 使用Get方法获取字符串结果(没有加入Cookie)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, Encoding encoding = null)
        {
            HttpClient httpClient = new HttpClient();
            var data = http://www.mamicode.com/await httpClient.GetByteArrayAsync(url);"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方法

 /// <summary>
        /// POST 异步
        /// </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 = http://www.mamicode.com/null,  Encoding encoding = null, int timeOut = 10000 )"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 同步
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postStream"></param>
        /// <param name="encoding"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static string HttpPost(string url, Dictionary<string, string> formData = http://www.mamicode.com/null, Encoding encoding = null, int timeOut = 10000)"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 t =   client.PostAsync(url, hc);
            t.Wait();
           var t2 =   t.Result.Content.ReadAsByteArrayAsync(); 
            return encoding.GetString(t2.Result);
        }
        /// <summary>
        /// 组装QueryString的方法
        /// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        public static string GetQueryString(this Dictionary<string, string> formData)
        {
            if (formData =http://www.mamicode.com/= null || formData.Count == 0)"";
            }

            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
        /// </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 =http://www.mamicode.com/= null ? new byte[0] : Encoding.UTF8.GetBytes(dataString);>

  

 

3 示例

修改View下面的index.cshtml文件

@{
    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 代码下载

链接: http://pan.baidu.com/s/1gfdqwDX 密码: dxzp

asp.net core中使用HttpClient实现Post和Get的同步异步方法