HttpClientManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. using System.Net.Sockets;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Collections.Specialized;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Net.Cache;
  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 = options.TimeoutMs;
  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. request.ServicePoint.BindIPEndPointDelegate = BindIPEndPointCallback;
  116. return request;
  117. }
  118. private static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
  119. {
  120. // Prefer local ipv4
  121. if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
  122. {
  123. return new IPEndPoint(IPAddress.IPv6Any, 0);
  124. }
  125. return new IPEndPoint(IPAddress.Any, 0);
  126. }
  127. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  128. {
  129. foreach (var header in options.RequestHeaders.ToList())
  130. {
  131. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  132. {
  133. request.Accept = header.Value;
  134. }
  135. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  136. {
  137. request.UserAgent = header.Value;
  138. }
  139. else
  140. {
  141. request.Headers.Set(header.Key, header.Value);
  142. }
  143. }
  144. }
  145. /// <summary>
  146. /// The _semaphoreLocks
  147. /// </summary>
  148. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(StringComparer.OrdinalIgnoreCase);
  149. /// <summary>
  150. /// Gets the lock.
  151. /// </summary>
  152. /// <param name="url">The filename.</param>
  153. /// <returns>System.Object.</returns>
  154. private SemaphoreSlim GetLock(string url)
  155. {
  156. return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1));
  157. }
  158. /// <summary>
  159. /// Gets the response internal.
  160. /// </summary>
  161. /// <param name="options">The options.</param>
  162. /// <returns>Task{HttpResponseInfo}.</returns>
  163. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  164. {
  165. return SendAsync(options, "GET");
  166. }
  167. /// <summary>
  168. /// Performs a GET request and returns the resulting stream
  169. /// </summary>
  170. /// <param name="options">The options.</param>
  171. /// <returns>Task{Stream}.</returns>
  172. public async Task<Stream> Get(HttpRequestOptions options)
  173. {
  174. var response = await GetResponse(options).ConfigureAwait(false);
  175. return response.Content;
  176. }
  177. /// <summary>
  178. /// Performs a GET request and returns the resulting stream
  179. /// </summary>
  180. /// <param name="url">The URL.</param>
  181. /// <param name="resourcePool">The resource pool.</param>
  182. /// <param name="cancellationToken">The cancellation token.</param>
  183. /// <returns>Task{Stream}.</returns>
  184. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  185. {
  186. return Get(new HttpRequestOptions
  187. {
  188. Url = url,
  189. ResourcePool = resourcePool,
  190. CancellationToken = cancellationToken,
  191. });
  192. }
  193. /// <summary>
  194. /// Gets the specified URL.
  195. /// </summary>
  196. /// <param name="url">The URL.</param>
  197. /// <param name="cancellationToken">The cancellation token.</param>
  198. /// <returns>Task{Stream}.</returns>
  199. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  200. {
  201. return Get(url, null, cancellationToken);
  202. }
  203. /// <summary>
  204. /// send as an asynchronous operation.
  205. /// </summary>
  206. /// <param name="options">The options.</param>
  207. /// <param name="httpMethod">The HTTP method.</param>
  208. /// <returns>Task{HttpResponseInfo}.</returns>
  209. /// <exception cref="HttpException">
  210. /// </exception>
  211. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  212. {
  213. HttpResponseInfo response;
  214. if (options.CacheMode == CacheMode.None)
  215. {
  216. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  217. return response;
  218. }
  219. var url = options.Url;
  220. var urlHash = url.ToLower().GetMD5().ToString("N");
  221. var semaphore = GetLock(url);
  222. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  223. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  224. if (response != null)
  225. {
  226. return response;
  227. }
  228. await semaphore.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  229. try
  230. {
  231. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  232. if (response != null)
  233. {
  234. return response;
  235. }
  236. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  237. if (response.StatusCode == HttpStatusCode.OK)
  238. {
  239. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  240. }
  241. return response;
  242. }
  243. finally
  244. {
  245. semaphore.Release();
  246. }
  247. }
  248. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  249. {
  250. try
  251. {
  252. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  253. {
  254. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  255. {
  256. var memoryStream = new MemoryStream();
  257. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  258. memoryStream.Position = 0;
  259. return new HttpResponseInfo
  260. {
  261. ResponseUrl = url,
  262. Content = memoryStream,
  263. StatusCode = HttpStatusCode.OK,
  264. Headers = new NameValueCollection(),
  265. ContentLength = memoryStream.Length
  266. };
  267. }
  268. }
  269. }
  270. catch (FileNotFoundException)
  271. {
  272. }
  273. catch (DirectoryNotFoundException)
  274. {
  275. }
  276. return null;
  277. }
  278. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  279. {
  280. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  281. using (var responseStream = response.Content)
  282. {
  283. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  284. {
  285. var memoryStream = new MemoryStream();
  286. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  287. memoryStream.Position = 0;
  288. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  289. memoryStream.Position = 0;
  290. response.Content = memoryStream;
  291. }
  292. }
  293. }
  294. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  295. {
  296. ValidateParams(options);
  297. options.CancellationToken.ThrowIfCancellationRequested();
  298. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  299. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  300. {
  301. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  302. {
  303. IsTimedOut = true
  304. };
  305. }
  306. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  307. if (options.RequestContentBytes != null ||
  308. !string.IsNullOrEmpty(options.RequestContent) ||
  309. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  310. {
  311. var bytes = options.RequestContentBytes ??
  312. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  313. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  314. httpWebRequest.ContentLength = bytes.Length;
  315. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  316. }
  317. if (options.ResourcePool != null)
  318. {
  319. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  320. }
  321. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  322. {
  323. if (options.ResourcePool != null)
  324. {
  325. options.ResourcePool.Release();
  326. }
  327. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  328. }
  329. if (options.LogRequest)
  330. {
  331. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  332. }
  333. try
  334. {
  335. options.CancellationToken.ThrowIfCancellationRequested();
  336. if (!options.BufferContent)
  337. {
  338. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  339. var httpResponse = (HttpWebResponse)response;
  340. EnsureSuccessStatusCode(httpResponse, options);
  341. options.CancellationToken.ThrowIfCancellationRequested();
  342. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  343. }
  344. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  345. {
  346. var httpResponse = (HttpWebResponse)response;
  347. EnsureSuccessStatusCode(httpResponse, options);
  348. options.CancellationToken.ThrowIfCancellationRequested();
  349. using (var stream = httpResponse.GetResponseStream())
  350. {
  351. var memoryStream = new MemoryStream();
  352. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  353. memoryStream.Position = 0;
  354. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  355. }
  356. }
  357. }
  358. catch (OperationCanceledException ex)
  359. {
  360. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  361. var httpException = exception as HttpException;
  362. if (httpException != null && httpException.IsTimedOut)
  363. {
  364. client.LastTimeout = DateTime.UtcNow;
  365. }
  366. throw exception;
  367. }
  368. catch (Exception ex)
  369. {
  370. throw GetException(ex, options);
  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, IDisposable disposable)
  398. {
  399. return new HttpResponseInfo(disposable)
  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 (Exception ex)
  519. {
  520. DeleteTempFile(tempFile);
  521. throw GetException(ex, options);
  522. }
  523. finally
  524. {
  525. if (options.ResourcePool != null)
  526. {
  527. options.ResourcePool.Release();
  528. }
  529. }
  530. }
  531. private long? GetContentLength(HttpWebResponse response)
  532. {
  533. var length = response.ContentLength;
  534. if (length == 0)
  535. {
  536. return null;
  537. }
  538. return length;
  539. }
  540. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  541. private Exception GetException(Exception ex, HttpRequestOptions options)
  542. {
  543. var webException = ex as WebException
  544. ?? ex.InnerException as WebException;
  545. if (webException != null)
  546. {
  547. return GetException(webException, options);
  548. }
  549. var operationCanceledException = ex as OperationCanceledException
  550. ?? ex.InnerException as OperationCanceledException;
  551. if (operationCanceledException != null)
  552. {
  553. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  554. }
  555. _logger.ErrorException("Error getting response from " + options.Url, ex);
  556. return ex;
  557. }
  558. private void DeleteTempFile(string file)
  559. {
  560. try
  561. {
  562. File.Delete(file);
  563. }
  564. catch (IOException)
  565. {
  566. // Might not have been created at all. No need to worry.
  567. }
  568. }
  569. private void ValidateParams(HttpRequestOptions options)
  570. {
  571. if (string.IsNullOrEmpty(options.Url))
  572. {
  573. throw new ArgumentNullException("options");
  574. }
  575. }
  576. /// <summary>
  577. /// Gets the host from URL.
  578. /// </summary>
  579. /// <param name="url">The URL.</param>
  580. /// <returns>System.String.</returns>
  581. private string GetHostFromUrl(string url)
  582. {
  583. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  584. var len = url.IndexOf('/', start) - start;
  585. return url.Substring(start, len);
  586. }
  587. /// <summary>
  588. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  589. /// </summary>
  590. public void Dispose()
  591. {
  592. Dispose(true);
  593. GC.SuppressFinalize(this);
  594. }
  595. /// <summary>
  596. /// Releases unmanaged and - optionally - managed resources.
  597. /// </summary>
  598. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  599. protected virtual void Dispose(bool dispose)
  600. {
  601. if (dispose)
  602. {
  603. _httpClients.Clear();
  604. }
  605. }
  606. /// <summary>
  607. /// Throws the cancellation exception.
  608. /// </summary>
  609. /// <param name="url">The URL.</param>
  610. /// <param name="cancellationToken">The cancellation token.</param>
  611. /// <param name="exception">The exception.</param>
  612. /// <returns>Exception.</returns>
  613. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  614. {
  615. // If the HttpClient's timeout is reached, it will cancel the Task internally
  616. if (!cancellationToken.IsCancellationRequested)
  617. {
  618. var msg = string.Format("Connection to {0} timed out", url);
  619. _logger.Error(msg);
  620. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  621. return new HttpException(msg, exception)
  622. {
  623. IsTimedOut = true
  624. };
  625. }
  626. return exception;
  627. }
  628. private void EnsureSuccessStatusCode(HttpWebResponse response, HttpRequestOptions options)
  629. {
  630. var statusCode = response.StatusCode;
  631. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  632. if (!isSuccessful)
  633. {
  634. if (options.LogErrorResponseBody)
  635. {
  636. try
  637. {
  638. using (var stream = response.GetResponseStream())
  639. {
  640. if (stream != null)
  641. {
  642. using (var reader = new StreamReader(stream))
  643. {
  644. var msg = reader.ReadToEnd();
  645. _logger.Error(msg);
  646. }
  647. }
  648. }
  649. }
  650. catch
  651. {
  652. }
  653. }
  654. throw new HttpException(response.StatusDescription)
  655. {
  656. StatusCode = response.StatusCode
  657. };
  658. }
  659. }
  660. /// <summary>
  661. /// Posts the specified URL.
  662. /// </summary>
  663. /// <param name="url">The URL.</param>
  664. /// <param name="postData">The post data.</param>
  665. /// <param name="cancellationToken">The cancellation token.</param>
  666. /// <returns>Task{Stream}.</returns>
  667. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  668. {
  669. return Post(url, postData, null, cancellationToken);
  670. }
  671. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  672. {
  673. var taskCompletion = new TaskCompletionSource<WebResponse>();
  674. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  675. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  676. asyncTask.ContinueWith(task =>
  677. {
  678. taskCompletion.TrySetResult(task.Result);
  679. }, TaskContinuationOptions.NotOnFaulted);
  680. // Handle errors
  681. asyncTask.ContinueWith(task =>
  682. {
  683. if (task.Exception != null)
  684. {
  685. taskCompletion.TrySetException(task.Exception);
  686. }
  687. else
  688. {
  689. taskCompletion.TrySetException(new List<Exception>());
  690. }
  691. }, TaskContinuationOptions.OnlyOnFaulted);
  692. return taskCompletion.Task;
  693. }
  694. private static void TimeoutCallback(object state, bool timedOut)
  695. {
  696. if (timedOut)
  697. {
  698. WebRequest request = (WebRequest)state;
  699. if (state != null)
  700. {
  701. request.Abort();
  702. }
  703. }
  704. }
  705. }
  706. }