【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; }