HttpClientManager.cs 26 KB

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