HttpClientService.cs
9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Rcs.Application.Shared;
namespace Rcs.Infrastructure.Shared;
/// <summary>
/// HTTP客户端服务实现
/// </summary>
public class HttpClientService : IHttpClientService
{
private readonly HttpClient _httpClient;
private readonly ILogger<HttpClientService> _logger;
private readonly JsonSerializerOptions _jsonOptions;
public HttpClientService(HttpClient httpClient, ILogger<HttpClientService> logger)
{
_httpClient = httpClient;
_logger = logger;
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
}
public async Task<TResponse?> GetAsync<TResponse>(
string url,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
AddHeaders(request, headers);
var response = await _httpClient.SendAsync(request, cancellationToken);
return await HandleResponse<TResponse>(response, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending GET request to {Url}", url);
throw;
}
}
public async Task<TResponse?> PostAsync<TRequest, TResponse>(
string url,
TRequest data,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Post, url);
AddHeaders(request, headers);
request.Content = CreateJsonContent(data);
_logger.LogInformation("Sending POST request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
return await HandleResponse<TResponse>(response, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending POST request to {Url}", url);
throw;
}
}
public async Task<HttpResponseMessage> PostAsync<TRequest>(
string url,
TRequest data,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Post, url);
AddHeaders(request, headers);
request.Content = CreateJsonContent(data);
_logger.LogInformation("Sending POST request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending POST request to {Url}", url);
throw;
}
}
public async Task<TResponse?> PutAsync<TRequest, TResponse>(
string url,
TRequest data,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Put, url);
AddHeaders(request, headers);
request.Content = CreateJsonContent(data);
_logger.LogInformation("Sending PUT request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
return await HandleResponse<TResponse>(response, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending PUT request to {Url}", url);
throw;
}
}
public async Task<HttpResponseMessage> PutAsync<TRequest>(
string url,
TRequest data,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Put, url);
AddHeaders(request, headers);
request.Content = CreateJsonContent(data);
_logger.LogInformation("Sending PUT request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending PUT request to {Url}", url);
throw;
}
}
public async Task<TResponse?> DeleteAsync<TResponse>(
string url,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Delete, url);
AddHeaders(request, headers);
_logger.LogInformation("Sending DELETE request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
return await HandleResponse<TResponse>(response, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending DELETE request to {Url}", url);
throw;
}
}
public async Task<HttpResponseMessage> DeleteAsync(
string url,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Delete, url);
AddHeaders(request, headers);
_logger.LogInformation("Sending DELETE request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending DELETE request to {Url}", url);
throw;
}
}
/// <summary>
/// 下载文件流
/// @author zzy
/// </summary>
public async Task<Stream> DownloadStreamAsync(
string url,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
AddHeaders(request, headers);
_logger.LogInformation("Downloading file from {Url}", url);
var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
var memoryStream = new MemoryStream();
await response.Content.CopyToAsync(memoryStream, cancellationToken);
memoryStream.Position = 0;
return memoryStream;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading file from {Url}", url);
throw;
}
}
public async Task<TResponse?> PatchAsync<TRequest, TResponse>(
string url,
TRequest data,
Dictionary<string, string>? headers = null,
CancellationToken cancellationToken = default)
{
try
{
using var request = new HttpRequestMessage(HttpMethod.Patch, url);
AddHeaders(request, headers);
request.Content = CreateJsonContent(data);
_logger.LogInformation("Sending PATCH request to {Url}", url);
var response = await _httpClient.SendAsync(request, cancellationToken);
return await HandleResponse<TResponse>(response, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending PATCH request to {Url}", url);
throw;
}
}
private void AddHeaders(HttpRequestMessage request, Dictionary<string, string>? headers)
{
if (headers == null) return;
foreach (var header in headers)
{
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
private HttpContent CreateJsonContent<T>(T data)
{
var json = JsonSerializer.Serialize(data, _jsonOptions);
return new StringContent(json, Encoding.UTF8, "application/json");
}
private async Task<TResponse?> HandleResponse<TResponse>(
HttpResponseMessage response,
CancellationToken cancellationToken)
{
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
_logger.LogError(
"HTTP request failed with status {StatusCode}. Response: {Response}",
response.StatusCode,
errorContent);
response.EnsureSuccessStatusCode();
}
var content = await response.Content.ReadAsStringAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(content))
{
return default;
}
return JsonSerializer.Deserialize<TResponse>(content, _jsonOptions);
}
}