HttpClientManager.cs 32 KB

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