HttpClientManager.cs 26 KB

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