-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathHttpClientAdapter.cs
313 lines (264 loc) · 12.3 KB
/
HttpClientAdapter.cs
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Octokit.Internal
{
/// <summary>
/// Generic Http client. Useful for those who want to swap out System.Net.HttpClient with something else.
/// </summary>
/// <remarks>
/// Most folks won't ever need to swap this out. But if you're trying to run this on Windows Phone, you might.
/// </remarks>
public class HttpClientAdapter : IHttpClient
{
readonly HttpClient _http;
public const string RedirectCountKey = "RedirectCount";
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public HttpClientAdapter(Func<HttpMessageHandler> getHandler)
{
Ensure.ArgumentNotNull(getHandler, nameof(getHandler));
_http = new HttpClient(new RedirectHandler { InnerHandler = getHandler() });
}
/// <summary>
/// Sends the specified request and returns a response.
/// </summary>
/// <param name="request">A <see cref="IRequest"/> that represents the HTTP request</param>
/// <param name="cancellationToken">Used to cancel the request</param>
/// <param name="preprocessResponseBody">Function to preprocess HTTP response prior to deserialization (can be null)</param>
/// <returns>A <see cref="Task" /> of <see cref="IResponse"/></returns>
public async Task<IResponse> Send(IRequest request, CancellationToken cancellationToken, Func<object, object> preprocessResponseBody = null)
{
Ensure.ArgumentNotNull(request, nameof(request));
var cancellationTokenForRequest = GetCancellationTokenForRequest(request, cancellationToken);
using (var requestMessage = BuildRequestMessage(request))
{
var responseMessage = await SendAsync(requestMessage, cancellationTokenForRequest).ConfigureAwait(false);
return await BuildResponse(responseMessage, preprocessResponseBody).ConfigureAwait(false);
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
static CancellationToken GetCancellationTokenForRequest(IRequest request, CancellationToken cancellationToken)
{
var cancellationTokenForRequest = cancellationToken;
if (request.Timeout != TimeSpan.Zero)
{
var timeoutCancellation = new CancellationTokenSource(request.Timeout);
var unifiedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellation.Token);
cancellationTokenForRequest = unifiedCancellationToken.Token;
}
return cancellationTokenForRequest;
}
protected virtual async Task<IResponse> BuildResponse(HttpResponseMessage responseMessage, Func<object, object> preprocessResponseBody)
{
Ensure.ArgumentNotNull(responseMessage, nameof(responseMessage));
object responseBody = null;
string contentType = null;
// We added support for downloading images,zip-files and application/octet-stream.
// Let's constrain this appropriately.
var binaryContentTypes = new[] {
AcceptHeaders.RawContentMediaType,
"application/zip" ,
"application/x-gzip" ,
"application/octet-stream"};
var content = responseMessage.Content;
if (content != null)
{
contentType = GetContentMediaType(content);
if (contentType != null && (contentType.StartsWith("image/") || binaryContentTypes
.Any(item => item.Equals(contentType, StringComparison.OrdinalIgnoreCase))))
{
responseBody = await content.ReadAsStreamAsync().ConfigureAwait(false);
}
else
{
responseBody = await content.ReadAsStringAsync().ConfigureAwait(false);
content.Dispose();
}
if (!(preprocessResponseBody is null))
responseBody = preprocessResponseBody(responseBody);
}
var responseHeaders = responseMessage.Headers.ToDictionary(h => h.Key, h => h.Value.First());
// Add Client response received time as a synthetic header
const string receivedTimeHeaderName = ApiInfoParser.ReceivedTimeHeaderName;
if (responseMessage.RequestMessage?.Properties is IDictionary<string, object> reqProperties
&& reqProperties.TryGetValue(receivedTimeHeaderName, out object receivedTimeObj)
&& receivedTimeObj is string receivedTimeString
&& !responseHeaders.ContainsKey(receivedTimeHeaderName))
{
responseHeaders[receivedTimeHeaderName] = receivedTimeString;
}
return new Response(
responseMessage.StatusCode,
responseBody,
responseHeaders,
contentType);
}
protected virtual HttpRequestMessage BuildRequestMessage(IRequest request)
{
Ensure.ArgumentNotNull(request, nameof(request));
HttpRequestMessage requestMessage = null;
try
{
var fullUri = new Uri(request.BaseAddress, request.Endpoint);
requestMessage = new HttpRequestMessage(request.Method, fullUri);
foreach (var header in request.Headers)
{
requestMessage.Headers.Add(header.Key, header.Value);
}
var httpContent = request.Body as HttpContent;
if (httpContent != null)
{
requestMessage.Content = httpContent;
}
var body = request.Body as string;
if (body != null)
{
requestMessage.Content = new StringContent(body, Encoding.UTF8, request.ContentType);
}
var bodyStream = request.Body as Stream;
if (bodyStream != null)
{
requestMessage.Content = new StreamContent(bodyStream);
requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(request.ContentType);
}
}
catch (Exception)
{
if (requestMessage != null)
{
requestMessage.Dispose();
}
throw;
}
return requestMessage;
}
static string GetContentMediaType(HttpContent httpContent)
{
if (httpContent.Headers?.ContentType != null)
{
return httpContent.Headers.ContentType.MediaType;
}
// Issue #2898 - Bad "zip" Content-Type coming from Blob Storage for artifacts
if (httpContent.Headers?.TryGetValues("Content-Type", out var contentTypeValues) == true
&& contentTypeValues.FirstOrDefault() == "zip")
{
return "application/zip";
}
return null;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_http != null) _http.Dispose();
}
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Clone the request/content in case we get a redirect
var clonedRequest = await CloneHttpRequestMessageAsync(request).ConfigureAwait(false);
// Send initial response
var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
// Need to determine time on client computer as soon as possible.
var receivedTime = DateTimeOffset.Now;
// Since Properties are stored as objects, serialize to HTTP round-tripping string (Format: r)
// Resolution is limited to one-second, matching the resolution of the HTTP Date header
request.Properties[ApiInfoParser.ReceivedTimeHeaderName] =
receivedTime.ToString("r", CultureInfo.InvariantCulture);
// Can't redirect without somewhere to redirect to.
if (response.Headers.Location == null)
{
return response;
}
// Don't redirect if we exceed max number of redirects
var redirectCount = 0;
if (request.Properties.Keys.Contains(RedirectCountKey))
{
redirectCount = (int)request.Properties[RedirectCountKey];
}
if (redirectCount > 3)
{
throw new InvalidOperationException("The redirect count for this request has been exceeded. Aborting.");
}
if (response.StatusCode == HttpStatusCode.MovedPermanently
|| response.StatusCode == HttpStatusCode.Redirect
|| response.StatusCode == HttpStatusCode.Found
|| response.StatusCode == HttpStatusCode.SeeOther
|| response.StatusCode == HttpStatusCode.TemporaryRedirect
|| (int)response.StatusCode == 308)
{
if (response.StatusCode == HttpStatusCode.SeeOther)
{
clonedRequest.Content = null;
clonedRequest.Method = HttpMethod.Get;
}
// Increment the redirect count
clonedRequest.Properties[RedirectCountKey] = ++redirectCount;
// Set the new Uri based on location header
clonedRequest.RequestUri = response.Headers.Location;
// Clear authentication if redirected to a different host
if (string.Compare(clonedRequest.RequestUri.Host, request.RequestUri.Host, StringComparison.OrdinalIgnoreCase) != 0)
{
clonedRequest.Headers.Authorization = null;
}
// Send redirected request
response = await SendAsync(clonedRequest, cancellationToken).ConfigureAwait(false);
}
return response;
}
public static async Task<HttpRequestMessage> CloneHttpRequestMessageAsync(HttpRequestMessage oldRequest)
{
var newRequest = new HttpRequestMessage(oldRequest.Method, oldRequest.RequestUri);
// Copy the request's content (via a MemoryStream) into the cloned object
var ms = new MemoryStream();
if (oldRequest.Content != null)
{
await oldRequest.Content.CopyToAsync(ms).ConfigureAwait(false);
ms.Position = 0;
newRequest.Content = new StreamContent(ms);
// Copy the content headers
if (oldRequest.Content.Headers != null)
{
foreach (var h in oldRequest.Content.Headers)
{
newRequest.Content.Headers.Add(h.Key, h.Value);
}
}
}
newRequest.Version = oldRequest.Version;
foreach (var header in oldRequest.Headers)
{
newRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
foreach (var property in oldRequest.Properties)
{
newRequest.Properties.Add(property);
}
return newRequest;
}
/// <summary>
/// Set the GitHub Api request timeout.
/// </summary>
/// <param name="timeout">The Timeout value</param>
public void SetRequestTimeout(TimeSpan timeout)
{
_http.Timeout = timeout;
}
}
internal class RedirectHandler : DelegatingHandler
{
}
}