YouDaoApiTools.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 HttpClient { 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 KeyValuePair<string, string>("q",System.Web.HttpUtility.UrlEncode(q, Encoding.UTF8)),//待翻译文本 必须是UTF-8编码
  57. new KeyValuePair<string, string>("q",q), //待翻译文本 必须是UTF-8编码
  58. new KeyValuePair<string, string>("from",from), //源语言
  59. new KeyValuePair<string, string>("to",to), //目标语言
  60. new KeyValuePair<string, string>("appKey",_appKey), //应用ID
  61. new KeyValuePair<string, string>("salt",salt), //UUID
  62. new KeyValuePair<string, string>("sign",sign), //签名
  63. new KeyValuePair<string, string>("signType","v3"), //签名类型
  64. new KeyValuePair<string, string>("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. /// <returns></returns>
  97. public static string SHA256EncryptString(string data)
  98. {
  99. byte[] bytes = Encoding.UTF8.GetBytes(data);
  100. byte[] hash = SHA256Managed.Create().ComputeHash(bytes);
  101. StringBuilder builder = new StringBuilder();
  102. for (int i = 0; i < hash.Length; i++)
  103. {
  104. builder.Append(hash[i].ToString("x2"));
  105. }
  106. return builder.ToString();
  107. }
  108. /// <summary>
  109. /// SHA256加密
  110. /// </summary>
  111. /// <param name="StrIn">待加密字符串</param>
  112. /// <returns>加密数组</returns>
  113. public static Byte[] SHA256EncryptByte(string StrIn)
  114. {
  115. var sha256 = new SHA256Managed();
  116. var Asc = new ASCIIEncoding();
  117. var tmpByte = Asc.GetBytes(StrIn);
  118. var EncryptBytes = sha256.ComputeHash(tmpByte);
  119. sha256.Clear();
  120. return EncryptBytes;
  121. }
  122. #endregion
  123. #region UTC时间戳
  124. /// <summary>
  125. /// 获取utc时间
  126. /// </summary>
  127. /// <param name="type">true 秒 flase 毫秒</param>
  128. /// <returns></returns>
  129. public static long GetUTCTime(bool type)
  130. {
  131. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  132. return type ? Convert.ToInt64(ts.TotalSeconds) : Convert.ToInt64(ts.TotalMilliseconds);
  133. }
  134. /// <summary>
  135. /// 将当前时间戳转换至Datetime
  136. /// </summary>
  137. /// <param name="timeStamp"></param>
  138. /// <returns></returns>
  139. public static DateTime ConvertUTCToDateTime(long timeStamp)
  140. {
  141. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
  142. DateTime dt = startTime.AddSeconds(timeStamp);
  143. return dt;
  144. }
  145. /// <summary>
  146. /// 把datetime转utc时间戳
  147. /// </summary>
  148. /// <param name="time"></param>
  149. /// <returns></returns>
  150. public static int ConvertDateTimeToUTC(DateTime time)
  151. {
  152. double intResult = 0;
  153. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  154. intResult = (time - startTime).TotalSeconds;
  155. return (int)intResult;
  156. }
  157. #endregion
  158. }
  159. }