HttpClientManager.cs 25 KB

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