HttpClientManager.cs 26 KB

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