HttpClientManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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. using CommonIO;
  21. namespace MediaBrowser.Common.Implementations.HttpClientManager
  22. {
  23. /// <summary>
  24. /// Class HttpClientManager
  25. /// </summary>
  26. public class HttpClientManager : IHttpClient
  27. {
  28. /// <summary>
  29. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  30. /// </summary>
  31. private const int TimeoutSeconds = 30;
  32. /// <summary>
  33. /// The _logger
  34. /// </summary>
  35. private readonly ILogger _logger;
  36. /// <summary>
  37. /// The _app paths
  38. /// </summary>
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly IFileSystem _fileSystem;
  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)
  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. _appPaths = appPaths;
  63. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  64. ServicePointManager.Expect100Continue = false;
  65. // Trakt requests sometimes fail without this
  66. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  67. }
  68. /// <summary>
  69. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  70. /// DON'T dispose it after use.
  71. /// </summary>
  72. /// <value>The HTTP clients.</value>
  73. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  74. /// <summary>
  75. /// Gets
  76. /// </summary>
  77. /// <param name="host">The host.</param>
  78. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  79. /// <returns>HttpClient.</returns>
  80. /// <exception cref="System.ArgumentNullException">host</exception>
  81. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  82. {
  83. if (string.IsNullOrEmpty(host))
  84. {
  85. throw new ArgumentNullException("host");
  86. }
  87. HttpClientInfo client;
  88. var key = host + enableHttpCompression;
  89. if (!_httpClients.TryGetValue(key, out client))
  90. {
  91. client = new HttpClientInfo();
  92. _httpClients.TryAdd(key, client);
  93. }
  94. return client;
  95. }
  96. private WebRequest CreateWebRequest(string url)
  97. {
  98. try
  99. {
  100. return WebRequest.Create(url);
  101. }
  102. catch (NotSupportedException)
  103. {
  104. //Webrequest creation does fail on MONO randomly when using WebRequest.Create
  105. //the issue occurs in the GetCreator method here: http://www.oschina.net/code/explore/mono-2.8.1/mcs/class/System/System.Net/WebRequest.cs
  106. var type = Type.GetType("System.Net.HttpRequestCreator, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089");
  107. var creator = Activator.CreateInstance(type, nonPublic: true) as IWebRequestCreate;
  108. return creator.Create(new Uri(url)) as HttpWebRequest;
  109. }
  110. }
  111. private WebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  112. {
  113. var request = CreateWebRequest(options.Url);
  114. var httpWebRequest = request as HttpWebRequest;
  115. if (httpWebRequest != null)
  116. {
  117. AddRequestHeaders(httpWebRequest, options);
  118. httpWebRequest.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  119. }
  120. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
  121. if (httpWebRequest != null)
  122. {
  123. if (options.EnableKeepAlive)
  124. {
  125. httpWebRequest.KeepAlive = true;
  126. }
  127. }
  128. request.Method = method;
  129. request.Timeout = options.TimeoutMs;
  130. if (httpWebRequest != null)
  131. {
  132. if (!string.IsNullOrEmpty(options.Host))
  133. {
  134. httpWebRequest.Host = options.Host;
  135. }
  136. if (!string.IsNullOrEmpty(options.Referer))
  137. {
  138. httpWebRequest.Referer = options.Referer;
  139. }
  140. }
  141. return request;
  142. }
  143. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  144. {
  145. foreach (var header in options.RequestHeaders.ToList())
  146. {
  147. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  148. {
  149. request.Accept = header.Value;
  150. }
  151. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  152. {
  153. request.UserAgent = header.Value;
  154. }
  155. else
  156. {
  157. request.Headers.Set(header.Key, header.Value);
  158. }
  159. }
  160. }
  161. /// <summary>
  162. /// Gets the response internal.
  163. /// </summary>
  164. /// <param name="options">The options.</param>
  165. /// <returns>Task{HttpResponseInfo}.</returns>
  166. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  167. {
  168. return SendAsync(options, "GET");
  169. }
  170. /// <summary>
  171. /// Performs a GET request and returns the resulting stream
  172. /// </summary>
  173. /// <param name="options">The options.</param>
  174. /// <returns>Task{Stream}.</returns>
  175. public async Task<Stream> Get(HttpRequestOptions options)
  176. {
  177. var response = await GetResponse(options).ConfigureAwait(false);
  178. return response.Content;
  179. }
  180. /// <summary>
  181. /// Performs a GET request and returns the resulting stream
  182. /// </summary>
  183. /// <param name="url">The URL.</param>
  184. /// <param name="resourcePool">The resource pool.</param>
  185. /// <param name="cancellationToken">The cancellation token.</param>
  186. /// <returns>Task{Stream}.</returns>
  187. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  188. {
  189. return Get(new HttpRequestOptions
  190. {
  191. Url = url,
  192. ResourcePool = resourcePool,
  193. CancellationToken = cancellationToken,
  194. });
  195. }
  196. /// <summary>
  197. /// Gets the specified URL.
  198. /// </summary>
  199. /// <param name="url">The URL.</param>
  200. /// <param name="cancellationToken">The cancellation token.</param>
  201. /// <returns>Task{Stream}.</returns>
  202. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  203. {
  204. return Get(url, null, cancellationToken);
  205. }
  206. /// <summary>
  207. /// send as an asynchronous operation.
  208. /// </summary>
  209. /// <param name="options">The options.</param>
  210. /// <param name="httpMethod">The HTTP method.</param>
  211. /// <returns>Task{HttpResponseInfo}.</returns>
  212. /// <exception cref="HttpException">
  213. /// </exception>
  214. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  215. {
  216. HttpResponseInfo response;
  217. if (options.CacheMode == CacheMode.None)
  218. {
  219. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  220. return response;
  221. }
  222. var url = options.Url;
  223. var urlHash = url.ToLower().GetMD5().ToString("N");
  224. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  225. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  226. if (response != null)
  227. {
  228. return response;
  229. }
  230. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  231. if (response.StatusCode == HttpStatusCode.OK)
  232. {
  233. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  234. }
  235. return response;
  236. }
  237. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  238. {
  239. try
  240. {
  241. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  242. {
  243. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  244. {
  245. var memoryStream = new MemoryStream();
  246. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  247. memoryStream.Position = 0;
  248. return new HttpResponseInfo
  249. {
  250. ResponseUrl = url,
  251. Content = memoryStream,
  252. StatusCode = HttpStatusCode.OK,
  253. Headers = new NameValueCollection(),
  254. ContentLength = memoryStream.Length
  255. };
  256. }
  257. }
  258. }
  259. catch (FileNotFoundException)
  260. {
  261. }
  262. catch (DirectoryNotFoundException)
  263. {
  264. }
  265. return null;
  266. }
  267. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  268. {
  269. _fileSystem.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  270. using (var responseStream = response.Content)
  271. {
  272. var memoryStream = new MemoryStream();
  273. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  274. memoryStream.Position = 0;
  275. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileMode.Create, FileAccess.Write, FileShare.None, true))
  276. {
  277. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  278. memoryStream.Position = 0;
  279. response.Content = memoryStream;
  280. }
  281. }
  282. }
  283. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  284. {
  285. ValidateParams(options);
  286. options.CancellationToken.ThrowIfCancellationRequested();
  287. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  288. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  289. {
  290. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  291. {
  292. IsTimedOut = true
  293. };
  294. }
  295. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  296. if (options.RequestContentBytes != null ||
  297. !string.IsNullOrEmpty(options.RequestContent) ||
  298. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  299. {
  300. var bytes = options.RequestContentBytes ??
  301. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  302. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  303. httpWebRequest.ContentLength = bytes.Length;
  304. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  305. }
  306. if (options.ResourcePool != null)
  307. {
  308. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  309. }
  310. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  311. {
  312. if (options.ResourcePool != null)
  313. {
  314. options.ResourcePool.Release();
  315. }
  316. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  317. }
  318. if (options.LogRequest)
  319. {
  320. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  321. }
  322. try
  323. {
  324. options.CancellationToken.ThrowIfCancellationRequested();
  325. if (!options.BufferContent)
  326. {
  327. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  328. var httpResponse = (HttpWebResponse)response;
  329. EnsureSuccessStatusCode(client, httpResponse, options);
  330. options.CancellationToken.ThrowIfCancellationRequested();
  331. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  332. }
  333. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  334. {
  335. var httpResponse = (HttpWebResponse)response;
  336. EnsureSuccessStatusCode(client, httpResponse, options);
  337. options.CancellationToken.ThrowIfCancellationRequested();
  338. using (var stream = httpResponse.GetResponseStream())
  339. {
  340. var memoryStream = new MemoryStream();
  341. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  342. memoryStream.Position = 0;
  343. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  344. }
  345. }
  346. }
  347. catch (OperationCanceledException ex)
  348. {
  349. throw GetCancellationException(options, client, options.CancellationToken, ex);
  350. }
  351. catch (Exception ex)
  352. {
  353. throw GetException(ex, options, client);
  354. }
  355. finally
  356. {
  357. if (options.ResourcePool != null)
  358. {
  359. options.ResourcePool.Release();
  360. }
  361. }
  362. }
  363. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  364. {
  365. return new HttpResponseInfo(disposable)
  366. {
  367. Content = content,
  368. StatusCode = httpResponse.StatusCode,
  369. ContentType = httpResponse.ContentType,
  370. Headers = new NameValueCollection(httpResponse.Headers),
  371. ContentLength = contentLength,
  372. ResponseUrl = httpResponse.ResponseUri.ToString()
  373. };
  374. }
  375. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  376. {
  377. return new HttpResponseInfo
  378. {
  379. TempFilePath = tempFile,
  380. StatusCode = httpResponse.StatusCode,
  381. ContentType = httpResponse.ContentType,
  382. Headers = httpResponse.Headers,
  383. ContentLength = contentLength
  384. };
  385. }
  386. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  387. {
  388. return SendAsync(options, "POST");
  389. }
  390. /// <summary>
  391. /// Performs a POST request
  392. /// </summary>
  393. /// <param name="options">The options.</param>
  394. /// <param name="postData">Params to add to the POST data.</param>
  395. /// <returns>stream on success, null on failure</returns>
  396. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  397. {
  398. options.SetPostData(postData);
  399. var response = await Post(options).ConfigureAwait(false);
  400. return response.Content;
  401. }
  402. /// <summary>
  403. /// Performs a POST request
  404. /// </summary>
  405. /// <param name="url">The URL.</param>
  406. /// <param name="postData">Params to add to the POST data.</param>
  407. /// <param name="resourcePool">The resource pool.</param>
  408. /// <param name="cancellationToken">The cancellation token.</param>
  409. /// <returns>stream on success, null on failure</returns>
  410. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  411. {
  412. return Post(new HttpRequestOptions
  413. {
  414. Url = url,
  415. ResourcePool = resourcePool,
  416. CancellationToken = cancellationToken
  417. }, postData);
  418. }
  419. /// <summary>
  420. /// Downloads the contents of a given url into a temporary location
  421. /// </summary>
  422. /// <param name="options">The options.</param>
  423. /// <returns>Task{System.String}.</returns>
  424. /// <exception cref="System.ArgumentNullException">progress</exception>
  425. public async Task<string> GetTempFile(HttpRequestOptions options)
  426. {
  427. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  428. return response.TempFilePath;
  429. }
  430. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  431. {
  432. ValidateParams(options);
  433. _fileSystem.CreateDirectory(_appPaths.TempDirectory);
  434. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  435. if (options.Progress == null)
  436. {
  437. throw new ArgumentNullException("progress");
  438. }
  439. options.CancellationToken.ThrowIfCancellationRequested();
  440. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  441. if (options.ResourcePool != null)
  442. {
  443. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  444. }
  445. options.Progress.Report(0);
  446. if (options.LogRequest)
  447. {
  448. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  449. }
  450. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  451. try
  452. {
  453. options.CancellationToken.ThrowIfCancellationRequested();
  454. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  455. {
  456. var httpResponse = (HttpWebResponse)response;
  457. EnsureSuccessStatusCode(client, httpResponse, options);
  458. options.CancellationToken.ThrowIfCancellationRequested();
  459. var contentLength = GetContentLength(httpResponse);
  460. if (!contentLength.HasValue)
  461. {
  462. // We're not able to track progress
  463. using (var stream = httpResponse.GetResponseStream())
  464. {
  465. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  466. {
  467. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  468. }
  469. }
  470. }
  471. else
  472. {
  473. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  474. {
  475. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  476. {
  477. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  478. }
  479. }
  480. }
  481. options.Progress.Report(100);
  482. return GetResponseInfo(httpResponse, tempFile, contentLength);
  483. }
  484. }
  485. catch (Exception ex)
  486. {
  487. DeleteTempFile(tempFile);
  488. throw GetException(ex, options, client);
  489. }
  490. finally
  491. {
  492. if (options.ResourcePool != null)
  493. {
  494. options.ResourcePool.Release();
  495. }
  496. }
  497. }
  498. private long? GetContentLength(HttpWebResponse response)
  499. {
  500. var length = response.ContentLength;
  501. if (length == 0)
  502. {
  503. return null;
  504. }
  505. return length;
  506. }
  507. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  508. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  509. {
  510. if (ex is HttpException)
  511. {
  512. return ex;
  513. }
  514. var webException = ex as WebException
  515. ?? ex.InnerException as WebException;
  516. if (webException != null)
  517. {
  518. if (options.LogErrors)
  519. {
  520. _logger.ErrorException("Error getting response from " + options.Url, ex);
  521. }
  522. var exception = new HttpException(ex.Message, ex);
  523. var response = webException.Response as HttpWebResponse;
  524. if (response != null)
  525. {
  526. exception.StatusCode = response.StatusCode;
  527. if ((int)response.StatusCode == 429)
  528. {
  529. client.LastTimeout = DateTime.UtcNow;
  530. }
  531. }
  532. return exception;
  533. }
  534. var operationCanceledException = ex as OperationCanceledException
  535. ?? ex.InnerException as OperationCanceledException;
  536. if (operationCanceledException != null)
  537. {
  538. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  539. }
  540. if (options.LogErrors)
  541. {
  542. _logger.ErrorException("Error getting response from " + options.Url, ex);
  543. }
  544. return ex;
  545. }
  546. private void DeleteTempFile(string file)
  547. {
  548. try
  549. {
  550. _fileSystem.DeleteFile(file);
  551. }
  552. catch (IOException)
  553. {
  554. // Might not have been created at all. No need to worry.
  555. }
  556. }
  557. private void ValidateParams(HttpRequestOptions options)
  558. {
  559. if (string.IsNullOrEmpty(options.Url))
  560. {
  561. throw new ArgumentNullException("options");
  562. }
  563. }
  564. /// <summary>
  565. /// Gets the host from URL.
  566. /// </summary>
  567. /// <param name="url">The URL.</param>
  568. /// <returns>System.String.</returns>
  569. private string GetHostFromUrl(string url)
  570. {
  571. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  572. if (index != -1)
  573. {
  574. url = url.Substring(index + 3);
  575. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  576. if (!string.IsNullOrWhiteSpace(host))
  577. {
  578. return host;
  579. }
  580. }
  581. return url;
  582. }
  583. /// <summary>
  584. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  585. /// </summary>
  586. public void Dispose()
  587. {
  588. Dispose(true);
  589. GC.SuppressFinalize(this);
  590. }
  591. /// <summary>
  592. /// Releases unmanaged and - optionally - managed resources.
  593. /// </summary>
  594. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  595. protected virtual void Dispose(bool dispose)
  596. {
  597. if (dispose)
  598. {
  599. _httpClients.Clear();
  600. }
  601. }
  602. /// <summary>
  603. /// Throws the cancellation exception.
  604. /// </summary>
  605. /// <param name="options">The options.</param>
  606. /// <param name="client">The client.</param>
  607. /// <param name="cancellationToken">The cancellation token.</param>
  608. /// <param name="exception">The exception.</param>
  609. /// <returns>Exception.</returns>
  610. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  611. {
  612. // If the HttpClient's timeout is reached, it will cancel the Task internally
  613. if (!cancellationToken.IsCancellationRequested)
  614. {
  615. var msg = string.Format("Connection to {0} timed out", options.Url);
  616. if (options.LogErrors)
  617. {
  618. _logger.Error(msg);
  619. }
  620. client.LastTimeout = DateTime.UtcNow;
  621. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  622. return new HttpException(msg, exception)
  623. {
  624. IsTimedOut = true
  625. };
  626. }
  627. return exception;
  628. }
  629. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  630. {
  631. var statusCode = response.StatusCode;
  632. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  633. if (!isSuccessful)
  634. {
  635. if (options.LogErrorResponseBody)
  636. {
  637. try
  638. {
  639. using (var stream = response.GetResponseStream())
  640. {
  641. if (stream != null)
  642. {
  643. using (var reader = new StreamReader(stream))
  644. {
  645. var msg = reader.ReadToEnd();
  646. _logger.Error(msg);
  647. }
  648. }
  649. }
  650. }
  651. catch
  652. {
  653. }
  654. }
  655. throw new HttpException(response.StatusDescription)
  656. {
  657. StatusCode = response.StatusCode
  658. };
  659. }
  660. }
  661. /// <summary>
  662. /// Posts the specified URL.
  663. /// </summary>
  664. /// <param name="url">The URL.</param>
  665. /// <param name="postData">The post data.</param>
  666. /// <param name="cancellationToken">The cancellation token.</param>
  667. /// <returns>Task{Stream}.</returns>
  668. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  669. {
  670. return Post(url, postData, null, cancellationToken);
  671. }
  672. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  673. {
  674. var taskCompletion = new TaskCompletionSource<WebResponse>();
  675. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  676. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  677. var callback = new TaskCallback { taskCompletion = taskCompletion };
  678. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  679. // Handle errors
  680. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  681. return taskCompletion.Task;
  682. }
  683. private static void TimeoutCallback(object state, bool timedOut)
  684. {
  685. if (timedOut)
  686. {
  687. WebRequest request = (WebRequest)state;
  688. if (state != null)
  689. {
  690. request.Abort();
  691. }
  692. }
  693. }
  694. private class TaskCallback
  695. {
  696. public TaskCompletionSource<WebResponse> taskCompletion;
  697. public void OnSuccess(Task<WebResponse> task)
  698. {
  699. taskCompletion.TrySetResult(task.Result);
  700. }
  701. public void OnError(Task<WebResponse> task)
  702. {
  703. if (task.Exception != null)
  704. {
  705. taskCompletion.TrySetException(task.Exception);
  706. }
  707. else
  708. {
  709. taskCompletion.TrySetException(new List<Exception>());
  710. }
  711. }
  712. }
  713. }
  714. }