HttpClientManager.cs 26 KB

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