2
0

HttpClientManager.cs 30 KB

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