1.在Program.cs中注入HttpClient服务
services.AddHttpClient();
public class HttpHelper { private readonly IHttpClientFactory _httpClient; public HttpHelper(IHttpClientFactory httpClient) { _httpClient = httpClient; } public async Task<string> HttpGet(string url, string param) { var client = _httpClient.CreateClient(); var response = await client.GetStringAsync( url ); TokenResultModel model = JsonConvert.DeserializeObject<TokenResultModel>( response ); return model.desc; } public async Task<object> HttpPost(string url,string param, Dictionary<string, string> head) { var client = _httpClient.CreateClient(); var content = new StringContent( param, Encoding.UTF8 ); foreach (var item in head) {
//表头字段中含有特殊字符"/" client.DefaultRequestHeaders.TryAddWithoutValidation( item.Key, item.Value ); } HttpResponseMessage response =client.PostAsync( url, content ).Result; var data = response.Content.ReadAsStringAsync().Result; return data; } }