HttpClientManager.cs 25 KB

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