| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- 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<HttpHelper> _logger;
- public HttpHelper(HttpClient client, ILogger<HttpHelper> logger)
- {
- _client = client;
- _logger = logger;
- }
- /// <summary>
- /// get请求
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <returns></returns>
- public async Task<string> 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 "";
- }
- }
- /// <summary>
- /// post请求
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="param">参数</param>
- /// <param name="contenttype">请求类型(默认application/json)</param>
- /// <returns></returns>
- public async Task<string> 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 "";
- }
- }
- /// <summary>
- /// put请求
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="param">参数</param>
- /// <param name="contenttype">请求类型(默认application/json)</param>
- /// <returns></returns>
- public async Task<string> 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 "";
- }
- }
- }
- }
|