HttpClient Get与Post请求数据

2021-04-19 22:27

阅读:637

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

直接干货:

public class HttpClientHelper
    {
        // 
        /// post 请求
        /// 
        /// 
        /// 
        /// 
        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)
            {
                Taskstring> t = res.Content.ReadAsStringAsync();
                return t.Result;
            }
            return string.Empty;
        }
        /// 
        /// Get 请求 
        /// 
        /// 
        /// 
        public static string GetResponse(string url)
        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage res = httpClient.GetAsync(url).Result;
            if (res.IsSuccessStatusCode)
            {
                Taskstring> 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 Dictionarystring, 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


评论


亲,登录后才可以留言!