HttpClient Get与Post请求数据

Posted fengge518

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient Get与Post请求数据相关的知识,希望对你有一定的参考价值。

直接干货:

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请求数据的主要内容,如果未能解决你的问题,请参考以下文章

使用httpclient发送post请求与get请求

HttpURLConnection与HttpClient浅析

HttpClient和AsynchttpClient的get与post请求方式

Java学习之HttpClient的GET与POST请求

HttpURLConnection与HttpClient浅析AAAA

HttpClient POST/SET方法