HttpClientManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Cache;
  14. using System.Net.Http;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Implementations.HttpClientManager
  20. {
  21. /// <summary>
  22. /// Class HttpClientManager
  23. /// </summary>
  24. public class HttpClientManager : IHttpClient
  25. {
  26. /// <summary>
  27. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  28. /// </summary>
  29. private int TimeoutSeconds = 30;
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// The _app paths
  36. /// </summary>
  37. private readonly IApplicationPaths _appPaths;
  38. private readonly IFileSystem _fileSystem;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="HttpClientManager"/> class.
  41. /// </summary>
  42. /// <param name="appPaths">The app paths.</param>
  43. /// <param name="logger">The logger.</param>
  44. /// <param name="getHttpClientHandler">The get HTTP client handler.</param>
  45. /// <exception cref="System.ArgumentNullException">
  46. /// appPaths
  47. /// or
  48. /// logger
  49. /// </exception>
  50. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  51. {
  52. if (appPaths == null)
  53. {
  54. throw new ArgumentNullException("appPaths");
  55. }
  56. if (logger == null)
  57. {
  58. throw new ArgumentNullException("logger");
  59. }
  60. _logger = logger;
  61. _fileSystem = fileSystem;
  62. _appPaths = appPaths;
  63. }
  64. /// <summary>
  65. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  66. /// DON'T dispose it after use.
  67. /// </summary>
  68. /// <value>The HTTP clients.</value>
  69. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  70. /// <summary>
  71. /// Gets
  72. /// </summary>
  73. /// <param name="host">The host.</param>
  74. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  75. /// <returns>HttpClient.</returns>
  76. /// <exception cref="System.ArgumentNullException">host</exception>
  77. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  78. {
  79. if (string.IsNullOrEmpty(host))
  80. {
  81. throw new ArgumentNullException("host");
  82. }
  83. HttpClientInfo client;
  84. var key = host + enableHttpCompression;
  85. if (!_httpClients.TryGetValue(key, out client))
  86. {
  87. client = new HttpClientInfo();
  88. _httpClients.TryAdd(key, client);
  89. }
  90. return client;
  91. }
  92. private PropertyInfo _httpBehaviorPropertyInfo;
  93. private HttpWebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  94. {
  95. var request = HttpWebRequest.CreateHttp(options.Url);
  96. if (!string.IsNullOrEmpty(options.AcceptHeader))
  97. {
  98. request.Accept = options.AcceptHeader;
  99. }
  100. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  101. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
  102. request.ConnectionGroupName = GetHostFromUrl(options.Url);
  103. request.KeepAlive = true;
  104. request.Method = method;
  105. request.Pipelined = true;
  106. request.Timeout = 20000;
  107. if (!string.IsNullOrEmpty(options.UserAgent))
  108. {
  109. request.UserAgent = options.UserAgent;
  110. }
  111. // This is a hack to prevent KeepAlive from getting disabled internally by the HttpWebRequest
  112. // May need to remove this for mono
  113. var sp = request.ServicePoint;
  114. if (_httpBehaviorPropertyInfo == null)
  115. {
  116. _httpBehaviorPropertyInfo = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
  117. }
  118. _httpBehaviorPropertyInfo.SetValue(sp, (byte)0, null);
  119. return request;
  120. }
  121. /// <summary>
  122. /// Gets the response internal.
  123. /// </summary>
  124. /// <param name="options">The options.</param>
  125. /// <param name="httpMethod">The HTTP method.</param>
  126. /// <returns>Task{HttpResponseInfo}.</returns>
  127. /// <exception cref="HttpException">
  128. /// </exception>
  129. public async Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  130. {
  131. ValidateParams(options.Url, options.CancellationToken);
  132. options.CancellationToken.ThrowIfCancellationRequested();
  133. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  134. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  135. {
  136. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url)) { IsTimedOut = true };
  137. }
  138. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  139. if (options.ResourcePool != null)
  140. {
  141. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  142. }
  143. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  144. {
  145. if (options.ResourcePool != null)
  146. {
  147. options.ResourcePool.Release();
  148. }
  149. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  150. }
  151. _logger.Info("HttpClientManager.GET url: {0}", options.Url);
  152. try
  153. {
  154. options.CancellationToken.ThrowIfCancellationRequested();
  155. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  156. {
  157. var httpResponse = (HttpWebResponse)response;
  158. EnsureSuccessStatusCode(httpResponse);
  159. options.CancellationToken.ThrowIfCancellationRequested();
  160. using (var stream = httpResponse.GetResponseStream())
  161. {
  162. var memoryStream = new MemoryStream();
  163. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  164. memoryStream.Position = 0;
  165. return new HttpResponseInfo
  166. {
  167. Content = memoryStream,
  168. StatusCode = httpResponse.StatusCode,
  169. ContentType = httpResponse.ContentType
  170. };
  171. }
  172. }
  173. }
  174. catch (OperationCanceledException ex)
  175. {
  176. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  177. var httpException = exception as HttpException;
  178. if (httpException != null && httpException.IsTimedOut)
  179. {
  180. client.LastTimeout = DateTime.UtcNow;
  181. }
  182. throw exception;
  183. }
  184. catch (HttpRequestException ex)
  185. {
  186. _logger.ErrorException("Error getting response from " + options.Url, ex);
  187. throw new HttpException(ex.Message, ex);
  188. }
  189. catch (WebException 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="options">The options.</param>
  211. /// <returns>Task{Stream}.</returns>
  212. /// <exception cref="HttpException"></exception>
  213. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  214. public async Task<Stream> Get(HttpRequestOptions options)
  215. {
  216. var response = await GetResponse(options).ConfigureAwait(false);
  217. return response.Content;
  218. }
  219. /// <summary>
  220. /// Performs a GET request and returns the resulting stream
  221. /// </summary>
  222. /// <param name="url">The URL.</param>
  223. /// <param name="resourcePool">The resource pool.</param>
  224. /// <param name="cancellationToken">The cancellation token.</param>
  225. /// <returns>Task{Stream}.</returns>
  226. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  227. {
  228. return Get(new HttpRequestOptions
  229. {
  230. Url = url,
  231. ResourcePool = resourcePool,
  232. CancellationToken = cancellationToken,
  233. });
  234. }
  235. /// <summary>
  236. /// Gets the specified URL.
  237. /// </summary>
  238. /// <param name="url">The URL.</param>
  239. /// <param name="cancellationToken">The cancellation token.</param>
  240. /// <returns>Task{Stream}.</returns>
  241. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  242. {
  243. return Get(url, null, cancellationToken);
  244. }
  245. /// <summary>
  246. /// Performs a POST request
  247. /// </summary>
  248. /// <param name="options">The options.</param>
  249. /// <param name="postData">Params to add to the POST data.</param>
  250. /// <returns>stream on success, null on failure</returns>
  251. /// <exception cref="HttpException">
  252. /// </exception>
  253. /// <exception cref="System.ArgumentNullException">postData</exception>
  254. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  255. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  256. {
  257. ValidateParams(options.Url, options.CancellationToken);
  258. options.CancellationToken.ThrowIfCancellationRequested();
  259. var httpWebRequest = GetRequest(options, "POST", options.EnableHttpCompression);
  260. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  261. var postContent = string.Join("&", strings.ToArray());
  262. var bytes = Encoding.UTF8.GetBytes(postContent);
  263. httpWebRequest.ContentType = "application/x-www-form-urlencoded";
  264. httpWebRequest.ContentLength = bytes.Length;
  265. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  266. if (options.ResourcePool != null)
  267. {
  268. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  269. }
  270. _logger.Info("HttpClientManager.POST url: {0}", options.Url);
  271. try
  272. {
  273. options.CancellationToken.ThrowIfCancellationRequested();
  274. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  275. {
  276. var httpResponse = (HttpWebResponse)response;
  277. EnsureSuccessStatusCode(httpResponse);
  278. options.CancellationToken.ThrowIfCancellationRequested();
  279. using (var stream = httpResponse.GetResponseStream())
  280. {
  281. var memoryStream = new MemoryStream();
  282. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  283. memoryStream.Position = 0;
  284. return memoryStream;
  285. }
  286. }
  287. }
  288. catch (OperationCanceledException ex)
  289. {
  290. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  291. throw exception;
  292. }
  293. catch (HttpRequestException ex)
  294. {
  295. _logger.ErrorException("Error getting response from " + options.Url, ex);
  296. throw new HttpException(ex.Message, ex);
  297. }
  298. catch (WebException ex)
  299. {
  300. _logger.ErrorException("Error getting response from " + options.Url, ex);
  301. throw new HttpException(ex.Message, ex);
  302. }
  303. catch (Exception ex)
  304. {
  305. _logger.ErrorException("Error getting response from " + options.Url, ex);
  306. throw;
  307. }
  308. finally
  309. {
  310. if (options.ResourcePool != null)
  311. {
  312. options.ResourcePool.Release();
  313. }
  314. }
  315. }
  316. /// <summary>
  317. /// Performs a POST request
  318. /// </summary>
  319. /// <param name="url">The URL.</param>
  320. /// <param name="postData">Params to add to the POST data.</param>
  321. /// <param name="resourcePool">The resource pool.</param>
  322. /// <param name="cancellationToken">The cancellation token.</param>
  323. /// <returns>stream on success, null on failure</returns>
  324. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  325. {
  326. return Post(new HttpRequestOptions
  327. {
  328. Url = url,
  329. ResourcePool = resourcePool,
  330. CancellationToken = cancellationToken
  331. }, postData);
  332. }
  333. /// <summary>
  334. /// Downloads the contents of a given url into a temporary location
  335. /// </summary>
  336. /// <param name="options">The options.</param>
  337. /// <returns>Task{System.String}.</returns>
  338. /// <exception cref="System.ArgumentNullException">progress</exception>
  339. /// <exception cref="HttpException"></exception>
  340. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  341. public async Task<string> GetTempFile(HttpRequestOptions options)
  342. {
  343. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  344. return response.TempFilePath;
  345. }
  346. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  347. {
  348. ValidateParams(options.Url, options.CancellationToken);
  349. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  350. if (options.Progress == null)
  351. {
  352. throw new ArgumentNullException("progress");
  353. }
  354. options.CancellationToken.ThrowIfCancellationRequested();
  355. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  356. if (options.ResourcePool != null)
  357. {
  358. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  359. }
  360. options.Progress.Report(0);
  361. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  362. try
  363. {
  364. options.CancellationToken.ThrowIfCancellationRequested();
  365. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  366. {
  367. var httpResponse = (HttpWebResponse)response;
  368. EnsureSuccessStatusCode(httpResponse);
  369. options.CancellationToken.ThrowIfCancellationRequested();
  370. var contentLength = GetContentLength(httpResponse);
  371. if (!contentLength.HasValue)
  372. {
  373. // We're not able to track progress
  374. using (var stream = httpResponse.GetResponseStream())
  375. {
  376. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  377. {
  378. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  379. }
  380. }
  381. }
  382. else
  383. {
  384. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  385. {
  386. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  387. {
  388. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  389. }
  390. }
  391. }
  392. options.Progress.Report(100);
  393. return new HttpResponseInfo
  394. {
  395. TempFilePath = tempFile,
  396. StatusCode = httpResponse.StatusCode,
  397. ContentType = httpResponse.ContentType
  398. };
  399. }
  400. }
  401. catch (OperationCanceledException ex)
  402. {
  403. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  404. throw exception;
  405. }
  406. catch (HttpRequestException ex)
  407. {
  408. _logger.ErrorException("Error getting response from " + options.Url, ex);
  409. throw new HttpException(ex.Message, ex);
  410. }
  411. catch (WebException ex)
  412. {
  413. _logger.ErrorException("Error getting response from " + options.Url, ex);
  414. throw new HttpException(ex.Message, ex);
  415. }
  416. catch (Exception ex)
  417. {
  418. _logger.ErrorException("Error getting response from " + options.Url, ex);
  419. throw;
  420. }
  421. finally
  422. {
  423. if (options.ResourcePool != null)
  424. {
  425. options.ResourcePool.Release();
  426. }
  427. }
  428. }
  429. /// <summary>
  430. /// Gets the message.
  431. /// </summary>
  432. /// <param name="options">The options.</param>
  433. /// <returns>HttpResponseMessage.</returns>
  434. private HttpRequestMessage GetHttpRequestMessage(HttpRequestOptions options)
  435. {
  436. var message = new HttpRequestMessage(HttpMethod.Get, options.Url);
  437. foreach (var pair in options.RequestHeaders.ToList())
  438. {
  439. if (!message.Headers.TryAddWithoutValidation(pair.Key, pair.Value))
  440. {
  441. _logger.Error("Unable to add request header {0} with value {1}", pair.Key, pair.Value);
  442. }
  443. }
  444. return message;
  445. }
  446. /// <summary>
  447. /// Gets the length of the content.
  448. /// </summary>
  449. /// <param name="response">The response.</param>
  450. /// <returns>System.Nullable{System.Int64}.</returns>
  451. private long? GetContentLength(HttpResponseMessage response)
  452. {
  453. IEnumerable<string> lengthValues = null;
  454. // Seeing some InvalidOperationException here under mono
  455. try
  456. {
  457. response.Headers.TryGetValues("content-length", out lengthValues);
  458. }
  459. catch (InvalidOperationException ex)
  460. {
  461. _logger.ErrorException("Error accessing response.Headers.TryGetValues Content-Length", ex);
  462. }
  463. if (lengthValues == null)
  464. {
  465. try
  466. {
  467. response.Content.Headers.TryGetValues("content-length", out lengthValues);
  468. }
  469. catch (InvalidOperationException ex)
  470. {
  471. _logger.ErrorException("Error accessing response.Content.Headers.TryGetValues Content-Length", ex);
  472. }
  473. }
  474. if (lengthValues == null)
  475. {
  476. return null;
  477. }
  478. return long.Parse(string.Join(string.Empty, lengthValues.ToArray()), UsCulture);
  479. }
  480. private long? GetContentLength(HttpWebResponse response)
  481. {
  482. var length = response.ContentLength;
  483. if (length == 0)
  484. {
  485. return null;
  486. }
  487. return length;
  488. }
  489. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  490. /// <summary>
  491. /// Handles the temp file exception.
  492. /// </summary>
  493. /// <param name="ex">The ex.</param>
  494. /// <param name="options">The options.</param>
  495. /// <param name="tempFile">The temp file.</param>
  496. /// <returns>Task.</returns>
  497. /// <exception cref="HttpException"></exception>
  498. private Exception GetTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  499. {
  500. var operationCanceledException = ex as OperationCanceledException;
  501. if (operationCanceledException != null)
  502. {
  503. // Cleanup
  504. DeleteTempFile(tempFile);
  505. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  506. }
  507. _logger.ErrorException("Error getting response from " + options.Url, ex);
  508. var httpRequestException = ex as HttpRequestException;
  509. // Cleanup
  510. DeleteTempFile(tempFile);
  511. if (httpRequestException != null)
  512. {
  513. return new HttpException(ex.Message, ex);
  514. }
  515. return ex;
  516. }
  517. private void DeleteTempFile(string file)
  518. {
  519. try
  520. {
  521. File.Delete(file);
  522. }
  523. catch (IOException)
  524. {
  525. // Might not have been created at all. No need to worry.
  526. }
  527. }
  528. /// <summary>
  529. /// Validates the params.
  530. /// </summary>
  531. /// <param name="url">The URL.</param>
  532. /// <param name="cancellationToken">The cancellation token.</param>
  533. /// <exception cref="System.ArgumentNullException">url</exception>
  534. private void ValidateParams(string url, CancellationToken cancellationToken)
  535. {
  536. if (string.IsNullOrEmpty(url))
  537. {
  538. throw new ArgumentNullException("url");
  539. }
  540. }
  541. /// <summary>
  542. /// Gets the host from URL.
  543. /// </summary>
  544. /// <param name="url">The URL.</param>
  545. /// <returns>System.String.</returns>
  546. private string GetHostFromUrl(string url)
  547. {
  548. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  549. var len = url.IndexOf('/', start) - start;
  550. return url.Substring(start, len);
  551. }
  552. /// <summary>
  553. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  554. /// </summary>
  555. public void Dispose()
  556. {
  557. Dispose(true);
  558. GC.SuppressFinalize(this);
  559. }
  560. /// <summary>
  561. /// Releases unmanaged and - optionally - managed resources.
  562. /// </summary>
  563. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  564. protected virtual void Dispose(bool dispose)
  565. {
  566. if (dispose)
  567. {
  568. _httpClients.Clear();
  569. }
  570. }
  571. /// <summary>
  572. /// Throws the cancellation exception.
  573. /// </summary>
  574. /// <param name="url">The URL.</param>
  575. /// <param name="cancellationToken">The cancellation token.</param>
  576. /// <param name="exception">The exception.</param>
  577. /// <returns>Exception.</returns>
  578. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  579. {
  580. // If the HttpClient's timeout is reached, it will cancel the Task internally
  581. if (!cancellationToken.IsCancellationRequested)
  582. {
  583. var msg = string.Format("Connection to {0} timed out", url);
  584. _logger.Error(msg);
  585. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  586. return new HttpException(msg, exception) { IsTimedOut = true };
  587. }
  588. return exception;
  589. }
  590. /// <summary>
  591. /// Ensures the success status code.
  592. /// </summary>
  593. /// <param name="response">The response.</param>
  594. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  595. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  596. {
  597. if (!response.IsSuccessStatusCode)
  598. {
  599. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  600. }
  601. }
  602. private void EnsureSuccessStatusCode(HttpWebResponse response)
  603. {
  604. var statusCode = response.StatusCode;
  605. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  606. if (!isSuccessful)
  607. {
  608. throw new HttpException(response.StatusDescription) { StatusCode = response.StatusCode };
  609. }
  610. }
  611. /// <summary>
  612. /// Posts the specified URL.
  613. /// </summary>
  614. /// <param name="url">The URL.</param>
  615. /// <param name="postData">The post data.</param>
  616. /// <param name="cancellationToken">The cancellation token.</param>
  617. /// <returns>Task{Stream}.</returns>
  618. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  619. {
  620. return Post(url, postData, null, cancellationToken);
  621. }
  622. }
  623. }