HttpClientManager.cs 29 KB

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