其他分享
首页 > 其他分享> > 【HttpClient】常用的3个请求方式

【HttpClient】常用的3个请求方式

作者:互联网

前言

经常用到,做个记录

代码

        /// <summary>
        /// HttpGet请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        static async Task<string> HttpGet(string url)
        {
            HttpResponseMessage response = await _client.GetAsync(url);

            string result = string.Empty;
            if (response.IsSuccessStatusCode)
                result = await response.Content.ReadAsStringAsync();

            return result;
        }

        /// <summary>
        /// HttpPost请求,FromForm接收
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        static async Task<string> HttpPostForm(string url, Dictionary<string, string> dic)
        {
            var httpContent = new MultipartFormDataContent();
            foreach (var para in dic)
                httpContent.Add(new StringContent(para.Value), para.Key);

            HttpResponseMessage response = await _client.PostAsync(url, httpContent);

            string result = string.Empty;
            if (response.IsSuccessStatusCode)
                result = await response.Content.ReadAsStringAsync();

            return result;
        }

        /// <summary>
        /// HttpPost请求,FromBody接收
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        static async Task<string> HttpPostBody(string url, Dictionary<string, object> dic)
        {
            var p = System.Text.Json.JsonSerializer.Serialize(dic);//对象序列化为Json字符串

            HttpContent httpContent = new StringContent(p);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = await _client.PostAsync(url, httpContent);

            string result = string.Empty;
            if (response.IsSuccessStatusCode)
                result = await response.Content.ReadAsStringAsync();

            return result;
        }

 

标签:常用,请求,url,await,result,HttpClient,httpContent,response,string
来源: https://www.cnblogs.com/masonblog/p/15637224.html