using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; namespace Net6Demo_Api.Util { public class HttpHelper { private readonly HttpClient _client; private readonly ILogger _logger; public HttpHelper(HttpClient client, ILogger logger) { _client = client; _logger = logger; } /// /// get请求 /// /// 请求地址 /// public async Task GetAsync(string url) { var response = await _client.GetAsync(url); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); _logger.LogInformation("get请求url:" + url + ";返回结果:" + result); return result; } else { _logger.LogError("get请求url:"+ url +";返回结果:"+ response.ToJson()); return ""; } } /// /// post请求 /// /// 请求地址 /// 参数 /// 请求类型(默认application/json) /// public async Task PostAsync(string url, string? param = null, string contenttype = "application/json") { var requestContent = new StringContent(param ?? "", Encoding.UTF8, contenttype); var response = await _client.PostAsync(url, requestContent); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); return result; } else { _logger.LogError("post请求url:" + url + ";参数:" + param + "返回结果:" + response.ToJson()); return ""; } } /// /// put请求 /// /// 请求地址 /// 参数 /// 请求类型(默认application/json) /// public async Task PutAsync(string url, string? param = null, string contenttype = "application/json") { var requestContent = new StringContent(param ?? "", Encoding.UTF8, contenttype); var response = await _client.PutAsync(url, requestContent); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); return result; } else { _logger.LogError("put请求url:" + url + ";参数:" + param + "返回结果:" + response.ToJson()); return ""; } } } }