HttpClientManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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 MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  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. /// The _logger
  29. /// </summary>
  30. private readonly ILogger _logger;
  31. /// <summary>
  32. /// The _app paths
  33. /// </summary>
  34. private readonly IApplicationPaths _appPaths;
  35. private readonly IJsonSerializer _jsonSerializer;
  36. private readonly FileSystemRepository _cacheRepository;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  39. /// </summary>
  40. /// <param name="appPaths">The kernel.</param>
  41. /// <param name="logger">The logger.</param>
  42. /// <param name="jsonSerializer">The json serializer.</param>
  43. /// <exception cref="System.ArgumentNullException">
  44. /// appPaths
  45. /// or
  46. /// logger
  47. /// </exception>
  48. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IJsonSerializer jsonSerializer)
  49. {
  50. if (appPaths == null)
  51. {
  52. throw new ArgumentNullException("appPaths");
  53. }
  54. if (logger == null)
  55. {
  56. throw new ArgumentNullException("logger");
  57. }
  58. _logger = logger;
  59. _jsonSerializer = jsonSerializer;
  60. _appPaths = appPaths;
  61. _cacheRepository = new FileSystemRepository(Path.Combine(_appPaths.CachePath, "downloads"));
  62. }
  63. /// <summary>
  64. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  65. /// DON'T dispose it after use.
  66. /// </summary>
  67. /// <value>The HTTP clients.</value>
  68. private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
  69. /// <summary>
  70. /// Gets
  71. /// </summary>
  72. /// <param name="host">The host.</param>
  73. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  74. /// <returns>HttpClient.</returns>
  75. /// <exception cref="System.ArgumentNullException">host</exception>
  76. private HttpClient GetHttpClient(string host, bool enableHttpCompression)
  77. {
  78. if (string.IsNullOrEmpty(host))
  79. {
  80. throw new ArgumentNullException("host");
  81. }
  82. HttpClient client;
  83. var key = host + enableHttpCompression;
  84. if (!_httpClients.TryGetValue(key, out client))
  85. {
  86. var handler = new WebRequestHandler
  87. {
  88. CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache),
  89. AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None
  90. };
  91. client = new HttpClient(handler);
  92. client.Timeout = TimeSpan.FromSeconds(20);
  93. _httpClients.TryAdd(key, client);
  94. }
  95. return client;
  96. }
  97. /// <summary>
  98. /// Performs a GET request and returns the resulting stream
  99. /// </summary>
  100. /// <param name="options">The options.</param>
  101. /// <returns>Task{Stream}.</returns>
  102. /// <exception cref="HttpException"></exception>
  103. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  104. public async Task<Stream> Get(HttpRequestOptions options)
  105. {
  106. ValidateParams(options.Url, options.CancellationToken);
  107. HttpResponseInfo cachedInfo = null;
  108. var urlHash = options.Url.GetMD5().ToString();
  109. var cachedInfoPath = _cacheRepository.GetResourcePath(urlHash + ".js");
  110. var cachedReponsePath = _cacheRepository.GetResourcePath(urlHash + ".dat");
  111. if (options.EnableResponseCache)
  112. {
  113. try
  114. {
  115. cachedInfo = _jsonSerializer.DeserializeFromFile<HttpResponseInfo>(cachedInfoPath);
  116. }
  117. catch (FileNotFoundException)
  118. {
  119. }
  120. if (cachedInfo != null)
  121. {
  122. var now = DateTime.UtcNow;
  123. var isCacheValid = cachedInfo.Expires.HasValue ? cachedInfo.Expires.Value > now :
  124. !cachedInfo.MustRevalidate && !string.IsNullOrEmpty(cachedInfo.Etag) && (now - cachedInfo.RequestDate).TotalDays < 5;
  125. if (isCacheValid)
  126. {
  127. _logger.Debug("Cache is still valid for {0}", options.Url);
  128. try
  129. {
  130. return GetCachedResponse(cachedReponsePath);
  131. }
  132. catch (FileNotFoundException)
  133. {
  134. }
  135. }
  136. }
  137. }
  138. options.CancellationToken.ThrowIfCancellationRequested();
  139. using (var message = GetHttpRequestMessage(options))
  140. {
  141. if (options.EnableResponseCache && cachedInfo != null)
  142. {
  143. if (!string.IsNullOrEmpty(cachedInfo.Etag))
  144. {
  145. message.Headers.Add("If-None-Match", cachedInfo.Etag);
  146. }
  147. else if (cachedInfo.LastModified.HasValue)
  148. {
  149. message.Headers.IfModifiedSince = new DateTimeOffset(cachedInfo.LastModified.Value);
  150. }
  151. }
  152. if (options.ResourcePool != null)
  153. {
  154. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  155. }
  156. _logger.Info("HttpClientManager.Get url: {0}", options.Url);
  157. try
  158. {
  159. options.CancellationToken.ThrowIfCancellationRequested();
  160. var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).SendAsync(message, HttpCompletionOption.ResponseContentRead, options.CancellationToken).ConfigureAwait(false);
  161. if (options.EnableResponseCache)
  162. {
  163. if (response.StatusCode != HttpStatusCode.NotModified)
  164. {
  165. EnsureSuccessStatusCode(response);
  166. }
  167. options.CancellationToken.ThrowIfCancellationRequested();
  168. cachedInfo = UpdateInfoCache(cachedInfo, options.Url, cachedInfoPath, response);
  169. if (response.StatusCode == HttpStatusCode.NotModified)
  170. {
  171. _logger.Debug("Server indicates not modified for {0}. Returning cached result.", options.Url);
  172. return GetCachedResponse(cachedReponsePath);
  173. }
  174. if (!string.IsNullOrEmpty(cachedInfo.Etag) || cachedInfo.LastModified.HasValue ||
  175. (cachedInfo.Expires.HasValue && cachedInfo.Expires.Value > DateTime.UtcNow))
  176. {
  177. await UpdateResponseCache(response, cachedReponsePath).ConfigureAwait(false);
  178. return GetCachedResponse(cachedReponsePath);
  179. }
  180. }
  181. else
  182. {
  183. EnsureSuccessStatusCode(response);
  184. options.CancellationToken.ThrowIfCancellationRequested();
  185. }
  186. return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  187. }
  188. catch (OperationCanceledException ex)
  189. {
  190. throw GetCancellationException(options.Url, options.CancellationToken, ex);
  191. }
  192. catch (HttpRequestException ex)
  193. {
  194. _logger.ErrorException("Error getting response from " + options.Url, ex);
  195. throw new HttpException(ex.Message, ex);
  196. }
  197. catch (Exception ex)
  198. {
  199. _logger.ErrorException("Error getting response from " + options.Url, ex);
  200. throw;
  201. }
  202. finally
  203. {
  204. if (options.ResourcePool != null)
  205. {
  206. options.ResourcePool.Release();
  207. }
  208. }
  209. }
  210. }
  211. /// <summary>
  212. /// Performs a GET request and returns the resulting stream
  213. /// </summary>
  214. /// <param name="url">The URL.</param>
  215. /// <param name="resourcePool">The resource pool.</param>
  216. /// <param name="cancellationToken">The cancellation token.</param>
  217. /// <returns>Task{Stream}.</returns>
  218. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  219. {
  220. return Get(new HttpRequestOptions
  221. {
  222. Url = url,
  223. ResourcePool = resourcePool,
  224. CancellationToken = cancellationToken,
  225. });
  226. }
  227. /// <summary>
  228. /// Gets the specified URL.
  229. /// </summary>
  230. /// <param name="url">The URL.</param>
  231. /// <param name="cancellationToken">The cancellation token.</param>
  232. /// <returns>Task{Stream}.</returns>
  233. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  234. {
  235. return Get(url, null, cancellationToken);
  236. }
  237. /// <summary>
  238. /// Gets the cached response.
  239. /// </summary>
  240. /// <param name="responsePath">The response path.</param>
  241. /// <returns>Stream.</returns>
  242. private Stream GetCachedResponse(string responsePath)
  243. {
  244. return File.OpenRead(responsePath);
  245. }
  246. /// <summary>
  247. /// Updates the cache.
  248. /// </summary>
  249. /// <param name="cachedInfo">The cached info.</param>
  250. /// <param name="url">The URL.</param>
  251. /// <param name="path">The path.</param>
  252. /// <param name="response">The response.</param>
  253. private HttpResponseInfo UpdateInfoCache(HttpResponseInfo cachedInfo, string url, string path, HttpResponseMessage response)
  254. {
  255. var fileExists = true;
  256. if (cachedInfo == null)
  257. {
  258. cachedInfo = new HttpResponseInfo();
  259. fileExists = false;
  260. }
  261. cachedInfo.Url = url;
  262. cachedInfo.RequestDate = DateTime.UtcNow;
  263. var etag = response.Headers.ETag;
  264. if (etag != null)
  265. {
  266. cachedInfo.Etag = etag.Tag;
  267. }
  268. var modified = response.Content.Headers.LastModified;
  269. if (modified.HasValue)
  270. {
  271. cachedInfo.LastModified = modified.Value.UtcDateTime;
  272. }
  273. else if (response.Headers.Age.HasValue)
  274. {
  275. cachedInfo.LastModified = DateTime.UtcNow.Subtract(response.Headers.Age.Value);
  276. }
  277. var expires = response.Content.Headers.Expires;
  278. if (expires.HasValue)
  279. {
  280. cachedInfo.Expires = expires.Value.UtcDateTime;
  281. }
  282. else
  283. {
  284. var cacheControl = response.Headers.CacheControl;
  285. if (cacheControl != null)
  286. {
  287. if (cacheControl.MaxAge.HasValue)
  288. {
  289. var baseline = cachedInfo.LastModified ?? DateTime.UtcNow;
  290. cachedInfo.Expires = baseline.Add(cacheControl.MaxAge.Value);
  291. }
  292. cachedInfo.MustRevalidate = cacheControl.MustRevalidate;
  293. }
  294. }
  295. if (string.IsNullOrEmpty(cachedInfo.Etag) && !cachedInfo.Expires.HasValue && !cachedInfo.LastModified.HasValue)
  296. {
  297. // Nothing to cache
  298. if (fileExists)
  299. {
  300. File.Delete(path);
  301. }
  302. }
  303. else
  304. {
  305. _jsonSerializer.SerializeToFile(cachedInfo, path);
  306. }
  307. return cachedInfo;
  308. }
  309. /// <summary>
  310. /// Updates the response cache.
  311. /// </summary>
  312. /// <param name="response">The response.</param>
  313. /// <param name="path">The path.</param>
  314. /// <returns>Task.</returns>
  315. private async Task UpdateResponseCache(HttpResponseMessage response, string path)
  316. {
  317. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  318. {
  319. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  320. {
  321. await stream.CopyToAsync(fs).ConfigureAwait(false);
  322. }
  323. }
  324. }
  325. /// <summary>
  326. /// Performs a POST request
  327. /// </summary>
  328. /// <param name="url">The URL.</param>
  329. /// <param name="postData">Params to add to the POST data.</param>
  330. /// <param name="resourcePool">The resource pool.</param>
  331. /// <param name="cancellationToken">The cancellation token.</param>
  332. /// <returns>stream on success, null on failure</returns>
  333. /// <exception cref="System.ArgumentNullException">postData</exception>
  334. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  335. public async Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  336. {
  337. ValidateParams(url, cancellationToken);
  338. if (postData == null)
  339. {
  340. throw new ArgumentNullException("postData");
  341. }
  342. cancellationToken.ThrowIfCancellationRequested();
  343. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  344. var postContent = string.Join("&", strings.ToArray());
  345. var content = new StringContent(postContent, Encoding.UTF8, "application/x-www-form-urlencoded");
  346. if (resourcePool != null)
  347. {
  348. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  349. }
  350. _logger.Info("HttpClientManager.Post url: {0}", url);
  351. try
  352. {
  353. cancellationToken.ThrowIfCancellationRequested();
  354. var msg = await GetHttpClient(GetHostFromUrl(url), false).PostAsync(url, content, cancellationToken).ConfigureAwait(false);
  355. EnsureSuccessStatusCode(msg);
  356. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  357. }
  358. catch (OperationCanceledException ex)
  359. {
  360. throw GetCancellationException(url, cancellationToken, ex);
  361. }
  362. catch (HttpRequestException ex)
  363. {
  364. _logger.ErrorException("Error getting response from " + url, ex);
  365. throw new HttpException(ex.Message, ex);
  366. }
  367. finally
  368. {
  369. if (resourcePool != null)
  370. {
  371. resourcePool.Release();
  372. }
  373. }
  374. }
  375. /// <summary>
  376. /// Downloads the contents of a given url into a temporary location
  377. /// </summary>
  378. /// <param name="options">The options.</param>
  379. /// <returns>Task{System.String}.</returns>
  380. /// <exception cref="System.ArgumentNullException">progress</exception>
  381. /// <exception cref="HttpException"></exception>
  382. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  383. public async Task<string> GetTempFile(HttpRequestOptions options)
  384. {
  385. ValidateParams(options.Url, options.CancellationToken);
  386. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  387. if (options.Progress == null)
  388. {
  389. throw new ArgumentNullException("progress");
  390. }
  391. options.CancellationToken.ThrowIfCancellationRequested();
  392. if (options.ResourcePool != null)
  393. {
  394. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  395. }
  396. options.Progress.Report(0);
  397. _logger.Info("HttpClientManager.GetTempFile url: {0}, temp file: {1}", options.Url, tempFile);
  398. try
  399. {
  400. options.CancellationToken.ThrowIfCancellationRequested();
  401. using (var message = GetHttpRequestMessage(options))
  402. {
  403. using (var response = await GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false))
  404. {
  405. EnsureSuccessStatusCode(response);
  406. options.CancellationToken.ThrowIfCancellationRequested();
  407. var contentLength = GetContentLength(response);
  408. if (!contentLength.HasValue)
  409. {
  410. // We're not able to track progress
  411. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  412. {
  413. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  414. {
  415. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  416. }
  417. }
  418. }
  419. else
  420. {
  421. using (var stream = ProgressStream.CreateReadProgressStream(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), options.Progress.Report, contentLength.Value))
  422. {
  423. using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  424. {
  425. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  426. }
  427. }
  428. }
  429. options.Progress.Report(100);
  430. options.CancellationToken.ThrowIfCancellationRequested();
  431. }
  432. }
  433. }
  434. catch (Exception ex)
  435. {
  436. HandleTempFileException(ex, options, tempFile);
  437. }
  438. finally
  439. {
  440. if (options.ResourcePool != null)
  441. {
  442. options.ResourcePool.Release();
  443. }
  444. }
  445. return tempFile;
  446. }
  447. /// <summary>
  448. /// Gets the message.
  449. /// </summary>
  450. /// <param name="options">The options.</param>
  451. /// <returns>HttpResponseMessage.</returns>
  452. private HttpRequestMessage GetHttpRequestMessage(HttpRequestOptions options)
  453. {
  454. var message = new HttpRequestMessage(HttpMethod.Get, options.Url);
  455. if (!string.IsNullOrEmpty(options.UserAgent))
  456. {
  457. message.Headers.Add("User-Agent", options.UserAgent);
  458. }
  459. if (!string.IsNullOrEmpty(options.AcceptHeader))
  460. {
  461. message.Headers.Add("Accept", options.AcceptHeader);
  462. }
  463. return message;
  464. }
  465. /// <summary>
  466. /// Gets the length of the content.
  467. /// </summary>
  468. /// <param name="response">The response.</param>
  469. /// <returns>System.Nullable{System.Int64}.</returns>
  470. private long? GetContentLength(HttpResponseMessage response)
  471. {
  472. IEnumerable<string> lengthValues;
  473. if (!response.Headers.TryGetValues("content-length", out lengthValues) && !response.Content.Headers.TryGetValues("content-length", out lengthValues))
  474. {
  475. return null;
  476. }
  477. return long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  478. }
  479. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  480. /// <summary>
  481. /// Handles the temp file exception.
  482. /// </summary>
  483. /// <param name="ex">The ex.</param>
  484. /// <param name="options">The options.</param>
  485. /// <param name="tempFile">The temp file.</param>
  486. /// <returns>Task.</returns>
  487. /// <exception cref="HttpException"></exception>
  488. private void HandleTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  489. {
  490. var operationCanceledException = ex as OperationCanceledException;
  491. if (operationCanceledException != null)
  492. {
  493. // Cleanup
  494. if (File.Exists(tempFile))
  495. {
  496. File.Delete(tempFile);
  497. }
  498. throw GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  499. }
  500. _logger.ErrorException("Error getting response from " + options.Url, ex);
  501. var httpRequestException = ex as HttpRequestException;
  502. // Cleanup
  503. if (File.Exists(tempFile))
  504. {
  505. File.Delete(tempFile);
  506. }
  507. if (httpRequestException != null)
  508. {
  509. throw new HttpException(ex.Message, ex);
  510. }
  511. throw ex;
  512. }
  513. /// <summary>
  514. /// Validates the params.
  515. /// </summary>
  516. /// <param name="url">The URL.</param>
  517. /// <param name="cancellationToken">The cancellation token.</param>
  518. /// <exception cref="System.ArgumentNullException">url</exception>
  519. private void ValidateParams(string url, CancellationToken cancellationToken)
  520. {
  521. if (string.IsNullOrEmpty(url))
  522. {
  523. throw new ArgumentNullException("url");
  524. }
  525. if (cancellationToken == null)
  526. {
  527. throw new ArgumentNullException("cancellationToken");
  528. }
  529. }
  530. /// <summary>
  531. /// Gets the host from URL.
  532. /// </summary>
  533. /// <param name="url">The URL.</param>
  534. /// <returns>System.String.</returns>
  535. private string GetHostFromUrl(string url)
  536. {
  537. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  538. var len = url.IndexOf('/', start) - start;
  539. return url.Substring(start, len);
  540. }
  541. /// <summary>
  542. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  543. /// </summary>
  544. public void Dispose()
  545. {
  546. Dispose(true);
  547. GC.SuppressFinalize(this);
  548. }
  549. /// <summary>
  550. /// Releases unmanaged and - optionally - managed resources.
  551. /// </summary>
  552. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  553. protected virtual void Dispose(bool dispose)
  554. {
  555. if (dispose)
  556. {
  557. foreach (var client in _httpClients.Values.ToList())
  558. {
  559. client.Dispose();
  560. }
  561. _httpClients.Clear();
  562. }
  563. }
  564. /// <summary>
  565. /// Throws the cancellation exception.
  566. /// </summary>
  567. /// <param name="url">The URL.</param>
  568. /// <param name="cancellationToken">The cancellation token.</param>
  569. /// <param name="exception">The exception.</param>
  570. /// <returns>Exception.</returns>
  571. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  572. {
  573. // If the HttpClient's timeout is reached, it will cancel the Task internally
  574. if (!cancellationToken.IsCancellationRequested)
  575. {
  576. var msg = string.Format("Connection to {0} timed out", url);
  577. _logger.Error(msg);
  578. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  579. return new HttpException(msg, exception) { IsTimedOut = true };
  580. }
  581. return exception;
  582. }
  583. /// <summary>
  584. /// Ensures the success status code.
  585. /// </summary>
  586. /// <param name="response">The response.</param>
  587. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  588. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  589. {
  590. if (!response.IsSuccessStatusCode)
  591. {
  592. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  593. }
  594. }
  595. /// <summary>
  596. /// Posts the specified URL.
  597. /// </summary>
  598. /// <param name="url">The URL.</param>
  599. /// <param name="postData">The post data.</param>
  600. /// <param name="cancellationToken">The cancellation token.</param>
  601. /// <returns>Task{Stream}.</returns>
  602. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  603. {
  604. return Post(url, postData, null, cancellationToken);
  605. }
  606. }
  607. }