HttpClientManager.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  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.Collections.Specialized;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Net.Cache;
  16. using System.Net.Http;
  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 WebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  96. {
  97. var request = (HttpWebRequest)WebRequest.Create(options.Url);
  98. AddRequestHeaders(request, options);
  99. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  100. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
  101. if (options.EnableKeepAlive)
  102. {
  103. request.KeepAlive = true;
  104. }
  105. request.Method = method;
  106. request.Timeout = 20000;
  107. if (!string.IsNullOrEmpty(options.Host))
  108. {
  109. request.Host = options.Host;
  110. }
  111. if (!string.IsNullOrEmpty(options.Referer))
  112. {
  113. request.Referer = options.Referer;
  114. }
  115. return request;
  116. }
  117. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  118. {
  119. foreach (var header in options.RequestHeaders.ToList())
  120. {
  121. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  122. {
  123. request.Accept = header.Value;
  124. }
  125. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  126. {
  127. request.UserAgent = header.Value;
  128. }
  129. else
  130. {
  131. request.Headers.Set(header.Key, header.Value);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// The _semaphoreLocks
  137. /// </summary>
  138. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(StringComparer.OrdinalIgnoreCase);
  139. /// <summary>
  140. /// Gets the lock.
  141. /// </summary>
  142. /// <param name="url">The filename.</param>
  143. /// <returns>System.Object.</returns>
  144. private SemaphoreSlim GetLock(string url)
  145. {
  146. return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1));
  147. }
  148. /// <summary>
  149. /// Gets the response internal.
  150. /// </summary>
  151. /// <param name="options">The options.</param>
  152. /// <returns>Task{HttpResponseInfo}.</returns>
  153. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  154. {
  155. return SendAsync(options, "GET");
  156. }
  157. /// <summary>
  158. /// Performs a GET request and returns the resulting stream
  159. /// </summary>
  160. /// <param name="options">The options.</param>
  161. /// <returns>Task{Stream}.</returns>
  162. public async Task<Stream> Get(HttpRequestOptions options)
  163. {
  164. var response = await GetResponse(options).ConfigureAwait(false);
  165. return response.Content;
  166. }
  167. /// <summary>
  168. /// Performs a GET request and returns the resulting stream
  169. /// </summary>
  170. /// <param name="url">The URL.</param>
  171. /// <param name="resourcePool">The resource pool.</param>
  172. /// <param name="cancellationToken">The cancellation token.</param>
  173. /// <returns>Task{Stream}.</returns>
  174. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  175. {
  176. return Get(new HttpRequestOptions
  177. {
  178. Url = url,
  179. ResourcePool = resourcePool,
  180. CancellationToken = cancellationToken,
  181. });
  182. }
  183. /// <summary>
  184. /// Gets the specified URL.
  185. /// </summary>
  186. /// <param name="url">The URL.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>Task{Stream}.</returns>
  189. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  190. {
  191. return Get(url, null, cancellationToken);
  192. }
  193. /// <summary>
  194. /// send as an asynchronous operation.
  195. /// </summary>
  196. /// <param name="options">The options.</param>
  197. /// <param name="httpMethod">The HTTP method.</param>
  198. /// <returns>Task{HttpResponseInfo}.</returns>
  199. /// <exception cref="HttpException">
  200. /// </exception>
  201. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  202. {
  203. if (!options.EnableUnconditionalCache)
  204. {
  205. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  206. }
  207. var url = options.Url;
  208. var urlHash = url.ToLower().GetMD5().ToString("N");
  209. var semaphore = GetLock(url);
  210. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  211. var response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  212. if (response != null)
  213. {
  214. return response;
  215. }
  216. await semaphore.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  217. try
  218. {
  219. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  220. if (response != null)
  221. {
  222. return response;
  223. }
  224. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  225. if (response.StatusCode == HttpStatusCode.OK)
  226. {
  227. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  228. }
  229. return response;
  230. }
  231. finally
  232. {
  233. semaphore.Release();
  234. }
  235. }
  236. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  237. {
  238. try
  239. {
  240. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  241. {
  242. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  243. {
  244. var memoryStream = new MemoryStream();
  245. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  246. memoryStream.Position = 0;
  247. return new HttpResponseInfo
  248. {
  249. ResponseUrl = url,
  250. Content = memoryStream,
  251. StatusCode = HttpStatusCode.OK,
  252. Headers = new NameValueCollection(),
  253. ContentLength = memoryStream.Length
  254. };
  255. }
  256. }
  257. }
  258. catch (FileNotFoundException)
  259. {
  260. }
  261. catch (DirectoryNotFoundException)
  262. {
  263. }
  264. return null;
  265. }
  266. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  267. {
  268. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  269. using (var responseStream = response.Content)
  270. {
  271. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  272. {
  273. var memoryStream = new MemoryStream();
  274. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  275. memoryStream.Position = 0;
  276. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  277. memoryStream.Position = 0;
  278. response.Content = memoryStream;
  279. }
  280. }
  281. }
  282. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  283. {
  284. ValidateParams(options);
  285. options.CancellationToken.ThrowIfCancellationRequested();
  286. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  287. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  288. {
  289. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  290. {
  291. IsTimedOut = true
  292. };
  293. }
  294. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  295. if (options.RequestContentBytes != null ||
  296. !string.IsNullOrEmpty(options.RequestContent) ||
  297. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  298. {
  299. var bytes = options.RequestContentBytes ??
  300. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  301. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  302. httpWebRequest.ContentLength = bytes.Length;
  303. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  304. }
  305. if (options.ResourcePool != null)
  306. {
  307. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  308. }
  309. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  310. {
  311. if (options.ResourcePool != null)
  312. {
  313. options.ResourcePool.Release();
  314. }
  315. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  316. }
  317. if (options.LogRequest)
  318. {
  319. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  320. }
  321. try
  322. {
  323. options.CancellationToken.ThrowIfCancellationRequested();
  324. if (!options.BufferContent)
  325. {
  326. var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);
  327. var httpResponse = (HttpWebResponse)response;
  328. EnsureSuccessStatusCode(httpResponse, options);
  329. options.CancellationToken.ThrowIfCancellationRequested();
  330. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse));
  331. }
  332. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  333. {
  334. var httpResponse = (HttpWebResponse)response;
  335. EnsureSuccessStatusCode(httpResponse, options);
  336. options.CancellationToken.ThrowIfCancellationRequested();
  337. using (var stream = httpResponse.GetResponseStream())
  338. {
  339. var memoryStream = new MemoryStream();
  340. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  341. memoryStream.Position = 0;
  342. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length);
  343. }
  344. }
  345. }
  346. catch (OperationCanceledException ex)
  347. {
  348. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  349. var httpException = exception as HttpException;
  350. if (httpException != null && httpException.IsTimedOut)
  351. {
  352. client.LastTimeout = DateTime.UtcNow;
  353. }
  354. throw exception;
  355. }
  356. catch (HttpRequestException ex)
  357. {
  358. _logger.ErrorException("Error getting response from " + options.Url, ex);
  359. throw new HttpException(ex.Message, ex);
  360. }
  361. catch (WebException ex)
  362. {
  363. throw GetException(ex, options);
  364. }
  365. catch (Exception ex)
  366. {
  367. _logger.ErrorException("Error getting response from " + options.Url, ex);
  368. throw;
  369. }
  370. finally
  371. {
  372. if (options.ResourcePool != null)
  373. {
  374. options.ResourcePool.Release();
  375. }
  376. }
  377. }
  378. /// <summary>
  379. /// Gets the exception.
  380. /// </summary>
  381. /// <param name="ex">The ex.</param>
  382. /// <param name="options">The options.</param>
  383. /// <returns>HttpException.</returns>
  384. private HttpException GetException(WebException ex, HttpRequestOptions options)
  385. {
  386. _logger.ErrorException("Error getting response from " + options.Url, ex);
  387. var exception = new HttpException(ex.Message, ex);
  388. var response = ex.Response as HttpWebResponse;
  389. if (response != null)
  390. {
  391. exception.StatusCode = response.StatusCode;
  392. }
  393. return exception;
  394. }
  395. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength)
  396. {
  397. return new HttpResponseInfo
  398. {
  399. Content = content,
  400. StatusCode = httpResponse.StatusCode,
  401. ContentType = httpResponse.ContentType,
  402. Headers = new NameValueCollection(httpResponse.Headers),
  403. ContentLength = contentLength,
  404. ResponseUrl = httpResponse.ResponseUri.ToString()
  405. };
  406. }
  407. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  408. {
  409. return new HttpResponseInfo
  410. {
  411. TempFilePath = tempFile,
  412. StatusCode = httpResponse.StatusCode,
  413. ContentType = httpResponse.ContentType,
  414. Headers = httpResponse.Headers,
  415. ContentLength = contentLength
  416. };
  417. }
  418. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  419. {
  420. return SendAsync(options, "POST");
  421. }
  422. /// <summary>
  423. /// Performs a POST request
  424. /// </summary>
  425. /// <param name="options">The options.</param>
  426. /// <param name="postData">Params to add to the POST data.</param>
  427. /// <returns>stream on success, null on failure</returns>
  428. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  429. {
  430. options.SetPostData(postData);
  431. var response = await Post(options).ConfigureAwait(false);
  432. return response.Content;
  433. }
  434. /// <summary>
  435. /// Performs a POST request
  436. /// </summary>
  437. /// <param name="url">The URL.</param>
  438. /// <param name="postData">Params to add to the POST data.</param>
  439. /// <param name="resourcePool">The resource pool.</param>
  440. /// <param name="cancellationToken">The cancellation token.</param>
  441. /// <returns>stream on success, null on failure</returns>
  442. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  443. {
  444. return Post(new HttpRequestOptions
  445. {
  446. Url = url,
  447. ResourcePool = resourcePool,
  448. CancellationToken = cancellationToken
  449. }, postData);
  450. }
  451. /// <summary>
  452. /// Downloads the contents of a given url into a temporary location
  453. /// </summary>
  454. /// <param name="options">The options.</param>
  455. /// <returns>Task{System.String}.</returns>
  456. /// <exception cref="System.ArgumentNullException">progress</exception>
  457. public async Task<string> GetTempFile(HttpRequestOptions options)
  458. {
  459. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  460. return response.TempFilePath;
  461. }
  462. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  463. {
  464. ValidateParams(options);
  465. Directory.CreateDirectory(_appPaths.TempDirectory);
  466. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  467. if (options.Progress == null)
  468. {
  469. throw new ArgumentNullException("progress");
  470. }
  471. options.CancellationToken.ThrowIfCancellationRequested();
  472. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  473. if (options.ResourcePool != null)
  474. {
  475. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  476. }
  477. options.Progress.Report(0);
  478. if (options.LogRequest)
  479. {
  480. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  481. }
  482. try
  483. {
  484. options.CancellationToken.ThrowIfCancellationRequested();
  485. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  486. {
  487. var httpResponse = (HttpWebResponse)response;
  488. EnsureSuccessStatusCode(httpResponse, options);
  489. options.CancellationToken.ThrowIfCancellationRequested();
  490. var contentLength = GetContentLength(httpResponse);
  491. if (!contentLength.HasValue)
  492. {
  493. // We're not able to track progress
  494. using (var stream = httpResponse.GetResponseStream())
  495. {
  496. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  497. {
  498. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  499. }
  500. }
  501. }
  502. else
  503. {
  504. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  505. {
  506. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  507. {
  508. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  509. }
  510. }
  511. }
  512. options.Progress.Report(100);
  513. return GetResponseInfo(httpResponse, tempFile, contentLength);
  514. }
  515. }
  516. catch (OperationCanceledException ex)
  517. {
  518. throw GetTempFileException(ex, options, tempFile);
  519. }
  520. catch (HttpRequestException ex)
  521. {
  522. throw GetTempFileException(ex, options, tempFile);
  523. }
  524. catch (WebException ex)
  525. {
  526. throw GetTempFileException(ex, options, tempFile);
  527. }
  528. catch (Exception ex)
  529. {
  530. throw GetTempFileException(ex, options, tempFile);
  531. }
  532. finally
  533. {
  534. if (options.ResourcePool != null)
  535. {
  536. options.ResourcePool.Release();
  537. }
  538. }
  539. }
  540. private long? GetContentLength(HttpWebResponse response)
  541. {
  542. var length = response.ContentLength;
  543. if (length == 0)
  544. {
  545. return null;
  546. }
  547. return length;
  548. }
  549. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  550. /// <summary>
  551. /// Handles the temp file exception.
  552. /// </summary>
  553. /// <param name="ex">The ex.</param>
  554. /// <param name="options">The options.</param>
  555. /// <param name="tempFile">The temp file.</param>
  556. /// <returns>Task.</returns>
  557. /// <exception cref="HttpException"></exception>
  558. private Exception GetTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  559. {
  560. var operationCanceledException = ex as OperationCanceledException;
  561. if (operationCanceledException != null)
  562. {
  563. // Cleanup
  564. DeleteTempFile(tempFile);
  565. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  566. }
  567. _logger.ErrorException("Error getting response from " + options.Url, ex);
  568. // Cleanup
  569. DeleteTempFile(tempFile);
  570. var httpRequestException = ex as HttpRequestException;
  571. if (httpRequestException != null)
  572. {
  573. return new HttpException(ex.Message, ex);
  574. }
  575. var webException = ex as WebException;
  576. if (webException != null)
  577. {
  578. throw GetException(webException, options);
  579. }
  580. return ex;
  581. }
  582. private void DeleteTempFile(string file)
  583. {
  584. try
  585. {
  586. File.Delete(file);
  587. }
  588. catch (IOException)
  589. {
  590. // Might not have been created at all. No need to worry.
  591. }
  592. }
  593. private void ValidateParams(HttpRequestOptions options)
  594. {
  595. if (string.IsNullOrEmpty(options.Url))
  596. {
  597. throw new ArgumentNullException("options");
  598. }
  599. }
  600. /// <summary>
  601. /// Gets the host from URL.
  602. /// </summary>
  603. /// <param name="url">The URL.</param>
  604. /// <returns>System.String.</returns>
  605. private string GetHostFromUrl(string url)
  606. {
  607. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  608. var len = url.IndexOf('/', start) - start;
  609. return url.Substring(start, len);
  610. }
  611. /// <summary>
  612. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  613. /// </summary>
  614. public void Dispose()
  615. {
  616. Dispose(true);
  617. GC.SuppressFinalize(this);
  618. }
  619. /// <summary>
  620. /// Releases unmanaged and - optionally - managed resources.
  621. /// </summary>
  622. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  623. protected virtual void Dispose(bool dispose)
  624. {
  625. if (dispose)
  626. {
  627. _httpClients.Clear();
  628. }
  629. }
  630. /// <summary>
  631. /// Throws the cancellation exception.
  632. /// </summary>
  633. /// <param name="url">The URL.</param>
  634. /// <param name="cancellationToken">The cancellation token.</param>
  635. /// <param name="exception">The exception.</param>
  636. /// <returns>Exception.</returns>
  637. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  638. {
  639. // If the HttpClient's timeout is reached, it will cancel the Task internally
  640. if (!cancellationToken.IsCancellationRequested)
  641. {
  642. var msg = string.Format("Connection to {0} timed out", url);
  643. _logger.Error(msg);
  644. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  645. return new HttpException(msg, exception)
  646. {
  647. IsTimedOut = true
  648. };
  649. }
  650. return exception;
  651. }
  652. private void EnsureSuccessStatusCode(HttpWebResponse response, HttpRequestOptions options)
  653. {
  654. var statusCode = response.StatusCode;
  655. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  656. if (!isSuccessful)
  657. {
  658. if (options.LogErrorResponseBody)
  659. {
  660. try
  661. {
  662. using (var stream = response.GetResponseStream())
  663. {
  664. if (stream != null)
  665. {
  666. using (var reader = new StreamReader(stream))
  667. {
  668. var msg = reader.ReadToEnd();
  669. _logger.Error(msg);
  670. }
  671. }
  672. }
  673. }
  674. catch
  675. {
  676. }
  677. }
  678. throw new HttpException(response.StatusDescription)
  679. {
  680. StatusCode = response.StatusCode
  681. };
  682. }
  683. }
  684. /// <summary>
  685. /// Posts the specified URL.
  686. /// </summary>
  687. /// <param name="url">The URL.</param>
  688. /// <param name="postData">The post data.</param>
  689. /// <param name="cancellationToken">The cancellation token.</param>
  690. /// <returns>Task{Stream}.</returns>
  691. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  692. {
  693. return Post(url, postData, null, cancellationToken);
  694. }
  695. }
  696. }