YouDaoApiTools.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. namespace OASystem.API.OAMethodLib.YouDaoAPI
  2. {
  3. /// <summary>
  4. /// 有道API Tools
  5. /// </summary>
  6. public static class YouDaoApiTools
  7. {
  8. private static readonly HttpClient _httpClient = new() { BaseAddress = new Uri("https://openapi.youdao.com") };
  9. //private static readonly IHttpClientFactory _httpClientFactory;
  10. private static readonly string _appKey = "0fe3bc01e109ed36"; //应用ID
  11. private static readonly string _appSecret = "1f2x9TrqJfSBEJ8iH9GEFGgTyaYGjEry"; //应用密钥
  12. #region OCR 调用翻译
  13. public static async Task<string> GetOCR_ReTrans(string txt)
  14. {
  15. var data = await GetReTrans(txt);
  16. string str;
  17. if (data == null && data.Code != 0)
  18. str = txt;
  19. else
  20. str = data.Data as string;
  21. return str;
  22. }
  23. #endregion
  24. /// <summary>
  25. /// 有道翻译
  26. /// 默认 中=>英
  27. /// </summary>
  28. /// <param name="txt">待翻译的文本</param>
  29. /// <param name="from">源语言</param>
  30. /// <param name="to">目标语言</param>
  31. /// <returns></returns>
  32. public static async Task<Result> GetReTrans(string txt, string from = "zh-CHS", string to = "en")
  33. {
  34. var result = new Result();
  35. #region MyRegion
  36. if (string.IsNullOrEmpty(txt))
  37. {
  38. result.Msg = "待翻译文本为空!";
  39. return result;
  40. }
  41. #endregion
  42. string url = string.Format("/api");
  43. #region 请求参数处理
  44. string q = txt;
  45. //input的计算方式为:input=q前10个字符 + q长度 + q后10个字符(当q长度大于20)或 input=q字符串(当q长度小于等于20);
  46. string input = q.Length <= 20 ? q : q.Substring(0, 10) + q.Length + q.Substring(q.Length - 10, 10);
  47. string salt = DateTime.Now.Millisecond.ToString();
  48. string curtime = GetUTCTime(true).ToString(); //UTC秒时间戳
  49. //sign = sha256(应用ID + input + salt + curtime + 应用密钥);
  50. string signStr = string.Format("{0}{1}{2}{3}{4}", _appKey, input, salt, curtime, _appSecret);
  51. string sign = SHA256EncryptString(signStr);
  52. #endregion
  53. var reqData = new FormUrlEncodedContent(
  54. new List<KeyValuePair<string, string>>()
  55. {
  56. //new("q",System.Web.HttpUtility.UrlEncode(q, Encoding.UTF8)),//待翻译文本 必须是UTF-8编码
  57. new("q",q), //待翻译文本 必须是UTF-8编码
  58. new("from",from), //源语言
  59. new("to",to), //目标语言
  60. new("appKey",_appKey), //应用ID
  61. new("salt",salt), //UUID
  62. new("sign",sign), //签名
  63. new("signType","v3"), //签名类型
  64. new("curtime",curtime), //TUC 时间戳
  65. });
  66. var reTransReq = await _httpClient.PostAsync(url, reqData);
  67. if (reTransReq.IsSuccessStatusCode)
  68. {
  69. var strResponse = await reTransReq.Content.ReadAsStringAsync();
  70. var strResponse1 = System.Web.HttpUtility.UrlDecode(strResponse, System.Text.Encoding.UTF8);
  71. var trans = JsonConvert.DeserializeObject<dynamic>(strResponse1);
  72. string errorCode = trans["errorCode"].ToString();
  73. if (errorCode == "0")
  74. {
  75. result.Code = 0;
  76. var translation = JsonConvert.DeserializeObject<List<string>>(trans["translation"].ToString());
  77. result.Msg = string.Format(@"成功!");
  78. result.Data = translation[0];
  79. }
  80. else
  81. {
  82. result.Msg = string.Format(@"有道翻译API [Error:{0}]", errorCode);
  83. }
  84. }
  85. else
  86. {
  87. result.Msg = "接口请求失败!";
  88. }
  89. return result;
  90. }
  91. #region SHA256加密
  92. /// <summary>
  93. /// SHA256加密
  94. /// </summary>
  95. /// <param name="data"></param>
  96. public static string SHA256EncryptString(string data)
  97. {
  98. byte[] bytes = Encoding.UTF8.GetBytes(data);
  99. byte[] hash = SHA256.Create().ComputeHash(bytes);
  100. StringBuilder builder = new StringBuilder();
  101. for (int i = 0; i < hash.Length; i++)
  102. {
  103. builder.Append(hash[i].ToString("x2"));
  104. }
  105. return builder.ToString();
  106. }
  107. /// <summary>
  108. /// SHA256加密
  109. /// </summary>
  110. /// <param name="StrIn">待加密字符串</param>
  111. /// <returns>加密数组</returns>
  112. public static Byte[] SHA256EncryptByte(string StrIn)
  113. {
  114. using var sha256 = SHA256.Create();
  115. var Asc = new ASCIIEncoding();
  116. var tmpByte = Asc.GetBytes(StrIn);
  117. var EncryptBytes = sha256.ComputeHash(tmpByte);
  118. return EncryptBytes;
  119. }
  120. #endregion
  121. #region UTC时间戳
  122. /// <summary>
  123. /// 获取utc时间
  124. /// </summary>
  125. /// <param name="type">true 秒 flase 毫秒</param>
  126. /// <returns></returns>
  127. public static long GetUTCTime(bool type)
  128. {
  129. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  130. return type ? Convert.ToInt64(ts.TotalSeconds) : Convert.ToInt64(ts.TotalMilliseconds);
  131. }
  132. ///// <summary>
  133. ///// 将当前时间戳转换至Datetime
  134. ///// </summary>
  135. ///// <param name="timeStamp"></param>
  136. ///// <returns></returns>
  137. //public static DateTime ConvertUTCToDateTime(long timeStamp)
  138. //{
  139. // DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
  140. // DateTime dt = startTime.AddSeconds(timeStamp);
  141. // return dt;
  142. //}
  143. ///// <summary>
  144. ///// 把datetime转utc时间戳
  145. ///// </summary>
  146. ///// <param name="time"></param>
  147. ///// <returns></returns>
  148. //public static int ConvertDateTimeToUTC(DateTime time)
  149. //{
  150. // double intResult = 0;
  151. // DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  152. // intResult = (time - startTime).TotalSeconds;
  153. // return (int)intResult;
  154. //}
  155. #endregion
  156. }
  157. }