1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using DataSharing.Share.Dtos.Province;
- using IdentityModel.Client;
- using Microsoft.AspNetCore.Http;
- using System.Net.Http.Headers;
- using System.Net.Http.Json;
- using System.Text;
- using XF.Domain.Dependency;
- using XF.Domain.Exceptions;
- namespace DataSharing;
- public class BaseHttpInvoker : IHttpInvoker, IScopeDependency
- {
- private readonly IHttpClientFactory _httpClientFactory;
- public BaseHttpInvoker(IHttpClientFactory httpClientFactory)
- {
- _httpClientFactory = httpClientFactory;
- }
- public async Task<TResponse?> RequestAsync<TRequest, TResponse>(
- TRequest request, Action<HttpClient>? setHttpClient = null, CancellationToken cancellationToken = default)
- where TRequest : ISharingRequest, new()
- {
- var httpClient = _httpClientFactory.CreateClient();
- if (setHttpClient != null)
- setHttpClient.Invoke(httpClient);
- var url = request.GetRequestUrl();
- var method = request.GetHttpMethod();
- var rsp = string.Empty;
- if (HttpMethods.IsGet(method))
- {
- rsp = await httpClient.GetStringAsync(url, cancellationToken);
- }
- else if (HttpMethods.IsPost(method))
- {
- using var responseMessage = await httpClient.PostAsJsonAsync(url, request, cancellationToken);
- responseMessage.EnsureSuccessStatusCode();
- using var responseContent = responseMessage.Content;
- rsp = await responseContent.ReadAsStringAsync(cancellationToken);
- }
- else
- {
- throw new UserFriendlyException("暂不支持该请求方式");
- }
- return System.Text.Json.JsonSerializer.Deserialize<TResponse>(rsp);
- }
- public async Task<TResponse?> RequestStringContentAsync<TResponse>(string url, string httpMethod, string? stringContent = null,
- Action<HttpClient>? setHttpClient = null, CancellationToken cancellationToken = default)
- {
- var httpClient = _httpClientFactory.CreateClient();
- if (setHttpClient != null)
- setHttpClient.Invoke(httpClient);
- var rsp = string.Empty;
- if (HttpMethods.IsGet(httpMethod))
- {
- rsp = await httpClient.GetStringAsync(url, cancellationToken);
- }
- else if (HttpMethods.IsPost(httpMethod))
- {
- using var responseMessage = await httpClient.PostAsync(url, new StringContent(stringContent, Encoding.UTF8, new MediaTypeWithQualityHeaderValue("application/json")),
- cancellationToken);
- responseMessage.EnsureSuccessStatusCode();
- using var responseContent = responseMessage.Content;
- rsp = await responseContent.ReadAsStringAsync(cancellationToken);
- }
- else
- {
- throw new UserFriendlyException("暂不支持该请求方式");
- }
- return System.Text.Json.JsonSerializer.Deserialize<TResponse>(rsp);
- }
- public async Task<TokenResponse> GetTokenAsync(ClientCredentialsTokenRequest request, CancellationToken cancellationToken)
- {
- var httpClient = _httpClientFactory.CreateClient();
- return await httpClient.RequestClientCredentialsTokenAsync(request, cancellationToken);
- }
- }
|