DtkApp.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using dodohold.core;
  2. using System.IO;
  3. using System.Net.Http;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace Dataoke
  7. {
  8. public class DtkApp
  9. {
  10. private string _appKey = "";
  11. private string _appSecret = "";
  12. public DtkApp(string appKey, string appSecret)
  13. {
  14. if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(appSecret))
  15. {
  16. Console.WriteLine("AppKey 和 AppSecret 必填!");
  17. throw new Exception("AppKey 和 AppSecret 必填!");
  18. }
  19. _appKey = appKey;
  20. _appSecret = appSecret;
  21. }
  22. public string Get(string apiUrl, string version, ApiParameters parameters)
  23. {
  24. try
  25. {
  26. string url = BuildUrl(apiUrl, version, parameters);
  27. using HttpClient client = new HttpClient();
  28. HttpResponseMessage response = client.GetAsync(url).Result;
  29. if (response.IsSuccessStatusCode)
  30. {
  31. Stream result2 = response.Content.ReadAsStreamAsync().Result;
  32. StreamReader streamReader = new StreamReader(result2, Encoding.GetEncoding("utf-8"));
  33. string result = streamReader.ReadToEnd();
  34. streamReader.Close();
  35. result2.Close();
  36. return result;
  37. }
  38. return response.StatusCode.ToString();
  39. }
  40. catch (Exception ex)
  41. {
  42. return ex.Message;
  43. }
  44. }
  45. private string BuildUrl(string apiUrl, string version, ApiParameters parameters)
  46. {
  47. int nonce;
  48. string timer;
  49. string sign = MakeSign(out nonce, out timer);
  50. if (sign == "")
  51. {
  52. return "";
  53. }
  54. string url = apiUrl.Trim() + "?appKey=" + _appKey.Trim() + "&nonce=" + nonce + "&signRan=" + sign + "&version=" + version.Trim() + "&timer=" + timer;
  55. if (parameters.Value.Count <= 0)
  56. {
  57. return url;
  58. }
  59. for (int i = 0; i <= parameters.Value.Count - 1; i++)
  60. {
  61. url += $"&{parameters.Value[i].Key}={parameters.Value[i].Value}";
  62. }
  63. return url;
  64. }
  65. public string MakeSign(out int nonce, out string timer)
  66. {
  67. Random rd = new Random();
  68. nonce = rd.Next(100000, 1000000);
  69. timer = GetTimeStamp();
  70. try
  71. {
  72. return $"appKey={_appKey}&timer={timer}&nonce={nonce}&key={_appSecret}".MD5(false, false);
  73. }
  74. catch (Exception)
  75. {
  76. return "";
  77. }
  78. }
  79. private static string GetTimeStamp()
  80. {
  81. return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds).ToString();
  82. }
  83. }
  84. }