HttpClientManager.cs 26 KB

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