2
0

HttpClientManager.cs 26 KB

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