HttpClientManager.cs 29 KB

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