HttpClientManager.cs 31 KB

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