HttpClientManager.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Net;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.Collections.Specialized;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Net.Cache;
  16. using System.Net.Http;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Common.Implementations.HttpClientManager
  21. {
  22. /// <summary>
  23. /// Class HttpClientManager
  24. /// </summary>
  25. public class HttpClientManager : IHttpClient
  26. {
  27. /// <summary>
  28. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  29. /// </summary>
  30. private const int TimeoutSeconds = 30;
  31. /// <summary>
  32. /// The _logger
  33. /// </summary>
  34. private readonly ILogger _logger;
  35. /// <summary>
  36. /// The _app paths
  37. /// </summary>
  38. private readonly IApplicationPaths _appPaths;
  39. private readonly IFileSystem _fileSystem;
  40. private readonly IConfigurationManager _config;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  43. /// </summary>
  44. /// <param name="appPaths">The app paths.</param>
  45. /// <param name="logger">The logger.</param>
  46. /// <param name="fileSystem">The file system.</param>
  47. /// <exception cref="System.ArgumentNullException">appPaths
  48. /// or
  49. /// logger</exception>
  50. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem, IConfigurationManager config)
  51. {
  52. if (appPaths == null)
  53. {
  54. throw new ArgumentNullException("appPaths");
  55. }
  56. if (logger == null)
  57. {
  58. throw new ArgumentNullException("logger");
  59. }
  60. _logger = logger;
  61. _fileSystem = fileSystem;
  62. _config = config;
  63. _appPaths = appPaths;
  64. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  65. ServicePointManager.Expect100Continue = false;
  66. }
  67. /// <summary>
  68. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  69. /// DON'T dispose it after use.
  70. /// </summary>
  71. /// <value>The HTTP clients.</value>
  72. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  73. /// <summary>
  74. /// Gets
  75. /// </summary>
  76. /// <param name="host">The host.</param>
  77. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  78. /// <returns>HttpClient.</returns>
  79. /// <exception cref="System.ArgumentNullException">host</exception>
  80. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  81. {
  82. if (string.IsNullOrEmpty(host))
  83. {
  84. throw new ArgumentNullException("host");
  85. }
  86. HttpClientInfo client;
  87. var key = host + enableHttpCompression;
  88. if (!_httpClients.TryGetValue(key, out client))
  89. {
  90. client = new HttpClientInfo();
  91. _httpClients.TryAdd(key, client);
  92. }
  93. return client;
  94. }
  95. private WebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  96. {
  97. var request = (HttpWebRequest)WebRequest.Create(options.Url);
  98. AddRequestHeaders(request, options);
  99. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  100. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
  101. if (options.EnableKeepAlive)
  102. {
  103. request.KeepAlive = true;
  104. }
  105. request.Method = method;
  106. request.Timeout = options.TimeoutMs;
  107. if (!string.IsNullOrEmpty(options.Host))
  108. {
  109. request.Host = options.Host;
  110. }
  111. if (!string.IsNullOrEmpty(options.Referer))
  112. {
  113. request.Referer = options.Referer;
  114. }
  115. return request;
  116. }
  117. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  118. {
  119. foreach (var header in options.RequestHeaders.ToList())
  120. {
  121. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  122. {
  123. request.Accept = header.Value;
  124. }
  125. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  126. {
  127. request.UserAgent = header.Value;
  128. }
  129. else
  130. {
  131. request.Headers.Set(header.Key, header.Value);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// The _semaphoreLocks
  137. /// </summary>
  138. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(StringComparer.OrdinalIgnoreCase);
  139. /// <summary>
  140. /// Gets the lock.
  141. /// </summary>
  142. /// <param name="url">The filename.</param>
  143. /// <returns>System.Object.</returns>
  144. private SemaphoreSlim GetLock(string url)
  145. {
  146. return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1));
  147. }
  148. /// <summary>
  149. /// Gets the response internal.
  150. /// </summary>
  151. /// <param name="options">The options.</param>
  152. /// <returns>Task{HttpResponseInfo}.</returns>
  153. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  154. {
  155. return SendAsync(options, "GET");
  156. }
  157. /// <summary>
  158. /// Performs a GET request and returns the resulting stream
  159. /// </summary>
  160. /// <param name="options">The options.</param>
  161. /// <returns>Task{Stream}.</returns>
  162. public async Task<Stream> Get(HttpRequestOptions options)
  163. {
  164. var response = await GetResponse(options).ConfigureAwait(false);
  165. return response.Content;
  166. }
  167. /// <summary>
  168. /// Performs a GET request and returns the resulting stream
  169. /// </summary>
  170. /// <param name="url">The URL.</param>
  171. /// <param name="resourcePool">The resource pool.</param>
  172. /// <param name="cancellationToken">The cancellation token.</param>
  173. /// <returns>Task{Stream}.</returns>
  174. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  175. {
  176. return Get(new HttpRequestOptions
  177. {
  178. Url = url,
  179. ResourcePool = resourcePool,
  180. CancellationToken = cancellationToken,
  181. });
  182. }
  183. /// <summary>
  184. /// Gets the specified URL.
  185. /// </summary>
  186. /// <param name="url">The URL.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>Task{Stream}.</returns>
  189. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  190. {
  191. return Get(url, null, cancellationToken);
  192. }
  193. /// <summary>
  194. /// send as an asynchronous operation.
  195. /// </summary>
  196. /// <param name="options">The options.</param>
  197. /// <param name="httpMethod">The HTTP method.</param>
  198. /// <returns>Task{HttpResponseInfo}.</returns>
  199. /// <exception cref="HttpException">
  200. /// </exception>
  201. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  202. {
  203. HttpResponseInfo response;
  204. if (options.CacheMode == CacheMode.None)
  205. {
  206. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  207. return response;
  208. }
  209. var url = options.Url;
  210. var urlHash = url.ToLower().GetMD5().ToString("N");
  211. var semaphore = GetLock(url);
  212. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  213. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  214. if (response != null)
  215. {
  216. return response;
  217. }
  218. await semaphore.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  219. try
  220. {
  221. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  222. if (response != null)
  223. {
  224. return response;
  225. }
  226. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  227. if (response.StatusCode == HttpStatusCode.OK)
  228. {
  229. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  230. }
  231. return response;
  232. }
  233. finally
  234. {
  235. semaphore.Release();
  236. }
  237. }
  238. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  239. {
  240. try
  241. {
  242. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  243. {
  244. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  245. {
  246. var memoryStream = new MemoryStream();
  247. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  248. memoryStream.Position = 0;
  249. return new HttpResponseInfo
  250. {
  251. ResponseUrl = url,
  252. Content = memoryStream,
  253. StatusCode = HttpStatusCode.OK,
  254. Headers = new NameValueCollection(),
  255. ContentLength = memoryStream.Length
  256. };
  257. }
  258. }
  259. }
  260. catch (FileNotFoundException)
  261. {
  262. }
  263. catch (DirectoryNotFoundException)
  264. {
  265. }
  266. return null;
  267. }
  268. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  269. {
  270. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  271. using (var responseStream = response.Content)
  272. {
  273. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  274. {
  275. var memoryStream = new MemoryStream();
  276. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  277. memoryStream.Position = 0;
  278. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  279. memoryStream.Position = 0;
  280. response.Content = memoryStream;
  281. }
  282. }
  283. }
  284. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  285. {
  286. ValidateParams(options);
  287. options.CancellationToken.ThrowIfCancellationRequested();
  288. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  289. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  290. {
  291. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  292. {
  293. IsTimedOut = true
  294. };
  295. }
  296. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  297. if (options.RequestContentBytes != null ||
  298. !string.IsNullOrEmpty(options.RequestContent) ||
  299. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  300. {
  301. var bytes = options.RequestContentBytes ??
  302. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  303. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  304. httpWebRequest.ContentLength = bytes.Length;
  305. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  306. }
  307. if (options.ResourcePool != null)
  308. {
  309. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  310. }
  311. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  312. {
  313. if (options.ResourcePool != null)
  314. {
  315. options.ResourcePool.Release();
  316. }
  317. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  318. }
  319. if (options.LogRequest)
  320. {
  321. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  322. }
  323. try
  324. {
  325. options.CancellationToken.ThrowIfCancellationRequested();
  326. if (!options.BufferContent)
  327. {
  328. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  329. var httpResponse = (HttpWebResponse)response;
  330. EnsureSuccessStatusCode(httpResponse, options);
  331. options.CancellationToken.ThrowIfCancellationRequested();
  332. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  333. }
  334. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  335. {
  336. var httpResponse = (HttpWebResponse)response;
  337. EnsureSuccessStatusCode(httpResponse, options);
  338. options.CancellationToken.ThrowIfCancellationRequested();
  339. using (var stream = httpResponse.GetResponseStream())
  340. {
  341. var memoryStream = new MemoryStream();
  342. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  343. memoryStream.Position = 0;
  344. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  345. }
  346. }
  347. }
  348. catch (OperationCanceledException ex)
  349. {
  350. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  351. var httpException = exception as HttpException;
  352. if (httpException != null && httpException.IsTimedOut)
  353. {
  354. client.LastTimeout = DateTime.UtcNow;
  355. }
  356. throw exception;
  357. }
  358. catch (Exception ex)
  359. {
  360. throw GetException(ex, options);
  361. }
  362. finally
  363. {
  364. if (options.ResourcePool != null)
  365. {
  366. options.ResourcePool.Release();
  367. }
  368. }
  369. }
  370. /// <summary>
  371. /// Gets the exception.
  372. /// </summary>
  373. /// <param name="ex">The ex.</param>
  374. /// <param name="options">The options.</param>
  375. /// <returns>HttpException.</returns>
  376. private HttpException GetException(WebException ex, HttpRequestOptions options)
  377. {
  378. _logger.ErrorException("Error getting response from " + options.Url, ex);
  379. var exception = new HttpException(ex.Message, ex);
  380. var response = ex.Response as HttpWebResponse;
  381. if (response != null)
  382. {
  383. exception.StatusCode = response.StatusCode;
  384. }
  385. return exception;
  386. }
  387. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  388. {
  389. return new HttpResponseInfo(disposable)
  390. {
  391. Content = content,
  392. StatusCode = httpResponse.StatusCode,
  393. ContentType = httpResponse.ContentType,
  394. Headers = new NameValueCollection(httpResponse.Headers),
  395. ContentLength = contentLength,
  396. ResponseUrl = httpResponse.ResponseUri.ToString()
  397. };
  398. }
  399. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  400. {
  401. return new HttpResponseInfo
  402. {
  403. TempFilePath = tempFile,
  404. StatusCode = httpResponse.StatusCode,
  405. ContentType = httpResponse.ContentType,
  406. Headers = httpResponse.Headers,
  407. ContentLength = contentLength
  408. };
  409. }
  410. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  411. {
  412. return SendAsync(options, "POST");
  413. }
  414. /// <summary>
  415. /// Performs a POST request
  416. /// </summary>
  417. /// <param name="options">The options.</param>
  418. /// <param name="postData">Params to add to the POST data.</param>
  419. /// <returns>stream on success, null on failure</returns>
  420. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  421. {
  422. options.SetPostData(postData);
  423. var response = await Post(options).ConfigureAwait(false);
  424. return response.Content;
  425. }
  426. /// <summary>
  427. /// Performs a POST request
  428. /// </summary>
  429. /// <param name="url">The URL.</param>
  430. /// <param name="postData">Params to add to the POST data.</param>
  431. /// <param name="resourcePool">The resource pool.</param>
  432. /// <param name="cancellationToken">The cancellation token.</param>
  433. /// <returns>stream on success, null on failure</returns>
  434. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  435. {
  436. return Post(new HttpRequestOptions
  437. {
  438. Url = url,
  439. ResourcePool = resourcePool,
  440. CancellationToken = cancellationToken
  441. }, postData);
  442. }
  443. /// <summary>
  444. /// Downloads the contents of a given url into a temporary location
  445. /// </summary>
  446. /// <param name="options">The options.</param>
  447. /// <returns>Task{System.String}.</returns>
  448. /// <exception cref="System.ArgumentNullException">progress</exception>
  449. public async Task<string> GetTempFile(HttpRequestOptions options)
  450. {
  451. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  452. return response.TempFilePath;
  453. }
  454. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  455. {
  456. ValidateParams(options);
  457. Directory.CreateDirectory(_appPaths.TempDirectory);
  458. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  459. if (options.Progress == null)
  460. {
  461. throw new ArgumentNullException("progress");
  462. }
  463. options.CancellationToken.ThrowIfCancellationRequested();
  464. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  465. if (options.ResourcePool != null)
  466. {
  467. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  468. }
  469. options.Progress.Report(0);
  470. if (options.LogRequest)
  471. {
  472. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  473. }
  474. try
  475. {
  476. options.CancellationToken.ThrowIfCancellationRequested();
  477. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  478. {
  479. var httpResponse = (HttpWebResponse)response;
  480. EnsureSuccessStatusCode(httpResponse, options);
  481. options.CancellationToken.ThrowIfCancellationRequested();
  482. var contentLength = GetContentLength(httpResponse);
  483. if (!contentLength.HasValue)
  484. {
  485. // We're not able to track progress
  486. using (var stream = httpResponse.GetResponseStream())
  487. {
  488. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  489. {
  490. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  491. }
  492. }
  493. }
  494. else
  495. {
  496. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  497. {
  498. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  499. {
  500. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  501. }
  502. }
  503. }
  504. options.Progress.Report(100);
  505. return GetResponseInfo(httpResponse, tempFile, contentLength);
  506. }
  507. }
  508. catch (Exception ex)
  509. {
  510. DeleteTempFile(tempFile);
  511. throw GetException(ex, options);
  512. }
  513. finally
  514. {
  515. if (options.ResourcePool != null)
  516. {
  517. options.ResourcePool.Release();
  518. }
  519. }
  520. }
  521. private long? GetContentLength(HttpWebResponse response)
  522. {
  523. var length = response.ContentLength;
  524. if (length == 0)
  525. {
  526. return null;
  527. }
  528. return length;
  529. }
  530. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  531. private Exception GetException(Exception ex, HttpRequestOptions options)
  532. {
  533. var webException = ex as WebException
  534. ?? ex.InnerException as WebException;
  535. if (webException != null)
  536. {
  537. return GetException(webException, options);
  538. }
  539. var operationCanceledException = ex as OperationCanceledException
  540. ?? ex.InnerException as OperationCanceledException;
  541. if (operationCanceledException != null)
  542. {
  543. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  544. }
  545. _logger.ErrorException("Error getting response from " + options.Url, ex);
  546. return ex;
  547. }
  548. private void DeleteTempFile(string file)
  549. {
  550. try
  551. {
  552. File.Delete(file);
  553. }
  554. catch (IOException)
  555. {
  556. // Might not have been created at all. No need to worry.
  557. }
  558. }
  559. private void ValidateParams(HttpRequestOptions options)
  560. {
  561. if (string.IsNullOrEmpty(options.Url))
  562. {
  563. throw new ArgumentNullException("options");
  564. }
  565. }
  566. /// <summary>
  567. /// Gets the host from URL.
  568. /// </summary>
  569. /// <param name="url">The URL.</param>
  570. /// <returns>System.String.</returns>
  571. private string GetHostFromUrl(string url)
  572. {
  573. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  574. var len = url.IndexOf('/', start) - start;
  575. return url.Substring(start, len);
  576. }
  577. /// <summary>
  578. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  579. /// </summary>
  580. public void Dispose()
  581. {
  582. Dispose(true);
  583. GC.SuppressFinalize(this);
  584. }
  585. /// <summary>
  586. /// Releases unmanaged and - optionally - managed resources.
  587. /// </summary>
  588. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  589. protected virtual void Dispose(bool dispose)
  590. {
  591. if (dispose)
  592. {
  593. _httpClients.Clear();
  594. }
  595. }
  596. /// <summary>
  597. /// Throws the cancellation exception.
  598. /// </summary>
  599. /// <param name="url">The URL.</param>
  600. /// <param name="cancellationToken">The cancellation token.</param>
  601. /// <param name="exception">The exception.</param>
  602. /// <returns>Exception.</returns>
  603. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  604. {
  605. // If the HttpClient's timeout is reached, it will cancel the Task internally
  606. if (!cancellationToken.IsCancellationRequested)
  607. {
  608. var msg = string.Format("Connection to {0} timed out", url);
  609. _logger.Error(msg);
  610. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  611. return new HttpException(msg, exception)
  612. {
  613. IsTimedOut = true
  614. };
  615. }
  616. return exception;
  617. }
  618. private void EnsureSuccessStatusCode(HttpWebResponse response, HttpRequestOptions options)
  619. {
  620. var statusCode = response.StatusCode;
  621. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  622. if (!isSuccessful)
  623. {
  624. if (options.LogErrorResponseBody)
  625. {
  626. try
  627. {
  628. using (var stream = response.GetResponseStream())
  629. {
  630. if (stream != null)
  631. {
  632. using (var reader = new StreamReader(stream))
  633. {
  634. var msg = reader.ReadToEnd();
  635. _logger.Error(msg);
  636. }
  637. }
  638. }
  639. }
  640. catch
  641. {
  642. }
  643. }
  644. throw new HttpException(response.StatusDescription)
  645. {
  646. StatusCode = response.StatusCode
  647. };
  648. }
  649. }
  650. /// <summary>
  651. /// Posts the specified URL.
  652. /// </summary>
  653. /// <param name="url">The URL.</param>
  654. /// <param name="postData">The post data.</param>
  655. /// <param name="cancellationToken">The cancellation token.</param>
  656. /// <returns>Task{Stream}.</returns>
  657. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  658. {
  659. return Post(url, postData, null, cancellationToken);
  660. }
  661. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  662. {
  663. var taskCompletion = new TaskCompletionSource<WebResponse>();
  664. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  665. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  666. asyncTask.ContinueWith(task =>
  667. {
  668. taskCompletion.TrySetResult(task.Result);
  669. }, TaskContinuationOptions.NotOnFaulted);
  670. // Handle errors
  671. asyncTask.ContinueWith(task =>
  672. {
  673. if (task.Exception != null)
  674. {
  675. taskCompletion.TrySetException(task.Exception);
  676. }
  677. else
  678. {
  679. taskCompletion.TrySetException(new List<Exception>());
  680. }
  681. }, TaskContinuationOptions.OnlyOnFaulted);
  682. return taskCompletion.Task;
  683. }
  684. private static void TimeoutCallback(object state, bool timedOut)
  685. {
  686. if (timedOut)
  687. {
  688. WebRequest request = (WebRequest)state;
  689. if (state != null)
  690. {
  691. request.Abort();
  692. }
  693. }
  694. }
  695. }
  696. }