码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient Get与Post请求数据

时间:2020-02-05 23:17:54      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:header   cat   success   stat   exception   ast   headers   throw   pre   

直接干货:

public class HttpClientHelper
    {
        // <summary>
        /// post 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static string PostXmlResponse(string url, string dataString)
        {
            HttpContent httpContent = new StringContent(dataString);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/josn");
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage res = httpClient.PostAsync(url, httpContent).Result;
            if (res.IsSuccessStatusCode)
            {
                Task<string> t = res.Content.ReadAsStringAsync();
                return t.Result;
            }
            return string.Empty;
        }
        /// <summary>
        /// Get 请求 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetResponse(string url)
        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage res = httpClient.GetAsync(url).Result;
            if (res.IsSuccessStatusCode)
            {
                Task<string> t = res.Content.ReadAsStringAsync();
                return t.Result;
            }
            return string.Empty;
        }
    }

 

 

Post 或者如下调用:

          try
            {
                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                var values = new Dictionary<string, string>
                {
                    { "cou_id", "A9E52C76-0CE7-4261-54C3-7EB04062F758" }
                };

                var content = new System.Net.Http.FormUrlEncodedContent(values);
                var response = httpClient.PostAsync("http://localhost:8888/Api/Course/GetCourseStudent", content).Result;
                var responseString = response.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

 

HttpClient Get与Post请求数据

标签:header   cat   success   stat   exception   ast   headers   throw   pre   

原文地址:https://www.cnblogs.com/Fengge518/p/12266911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!