HttpClientManager.cs 30 KB

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