TQHttpClient.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using Hotline.Share.Dtos.Snapshot;
  2. using Hotline.Share.Tools;
  3. using Microsoft.Extensions.Logging;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Serialization;
  6. using Renci.SshNet;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Net.Http.Headers;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace TianQue.Sdk;
  14. public class TQHttpClient
  15. {
  16. private readonly string AppSecret;
  17. private readonly string AppKey;
  18. private readonly IHttpClientFactory _httpClientFactory;
  19. /// <summary>
  20. /// ssh服务器ip
  21. /// </summary>
  22. private readonly string SSHHost;
  23. /// <summary>
  24. /// ssh服务器端口
  25. /// </summary>
  26. private readonly int SSHPort;
  27. /// <summary>
  28. /// ssh账号
  29. /// </summary>
  30. private readonly string SSHUserName;
  31. /// <summary>
  32. /// ssh密码
  33. /// </summary>
  34. private readonly string SSHPassword;
  35. private readonly SshClient _sshClient;
  36. private readonly ILogger<TQHttpClient> _logger;
  37. public TQHttpClient(string appSecret, string appKey, IHttpClientFactory httpClientFactory, ILogger<TQHttpClient> logger)
  38. {
  39. AppSecret = appSecret;
  40. AppKey = appKey;
  41. _httpClientFactory = httpClientFactory;
  42. _logger = logger;
  43. }
  44. public TQHttpClient(string appSecret, string appKey, string sshHost, int sshPort, string sshUserName, string sshPassword, IHttpClientFactory httpClientFactory, ILogger<TQHttpClient> logger)
  45. : this(appSecret, appKey, httpClientFactory, logger)
  46. {
  47. SSHHost = sshHost;
  48. SSHPort = sshPort;
  49. SSHUserName = sshUserName;
  50. SSHPassword = sshPassword;
  51. _sshClient = new SshClient(SSHHost, SSHPort, SSHUserName, SSHPassword);
  52. }
  53. public async Task<T> PostAsync<T>(Uri uri, object data)
  54. {
  55. try
  56. {
  57. var headers = new Dictionary<string, object> { { "_timeStamp", DateTime.Now.ToUnixTimeMilliseconds() }, { "_nonce", SignUtils.GenerateNonce() } };
  58. var sortedDic = new SortedDictionary<string, object>(data.ToDictionary());
  59. var body = sortedDic.ToJson(new JsonSerializerSettings
  60. {
  61. NullValueHandling = NullValueHandling.Ignore,
  62. ContractResolver = new CamelCasePropertyNamesContractResolver(),
  63. DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"
  64. });
  65. var postJsonSign = SignUtils.Sign(AppSecret, headers, body);
  66. headers.Add("_sign", postJsonSign);
  67. headers.Add("_appKey", AppKey);
  68. if (SSHHost.NotNullOrEmpty() && SSHPort != 0 && SSHUserName.NotNullOrEmpty() && SSHPassword.NotNullOrEmpty())
  69. {
  70. _sshClient.Connect();
  71. var forwardedPort = new ForwardedPortLocal("127.0.0.1", 8090, uri.Host, (uint)uri.Port);
  72. _sshClient.AddForwardedPort(forwardedPort);
  73. forwardedPort.Start();
  74. uri = new Uri("http://127.0.0.1:8090" + uri.AbsolutePath);
  75. }
  76. var content = new StringContent(body, Encoding.GetEncoding("UTF-8"));
  77. content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "UTF-8" };
  78. foreach (var header in headers)
  79. {
  80. content.Headers.Add(header.Key, header.Value.ToString());
  81. }
  82. var resp = await (_httpClientFactory.CreateClient()).PostAsync(uri.ToString(), content);
  83. resp.EnsureSuccessStatusCode();
  84. var result = await resp.Content.ReadAsStringAsync();
  85. _logger.LogInformation($"天阙交互; url: {uri.ToString()}, headers: {headers.ToJson()} request: {body}, response: {result}");
  86. return result.FromJson<T>();
  87. }
  88. catch (Exception e)
  89. {
  90. _logger.LogError(e.Message);
  91. throw;
  92. }
  93. finally
  94. {
  95. if (_sshClient.IsConnected)
  96. {
  97. _sshClient.Disconnect();
  98. }
  99. }
  100. }
  101. }