接入接口前首先需要申请应用ID和应用秘钥,登录有道智云AI开放平台,创建应用,获取应用ID和秘钥。
定义接口响应类数据结构,接口实际返回内容和官方文档有点出入,大概是文档未更新吧。
以下是官方文档给出的说明:
以下是本人测试获取到的响应结构:
定义该数据结构:
[Serializable]
public class Response
{/// <summary>/// 单词校验后的结果 主要校验字母大小写、单词前含符号、中文简繁体/// </summary>public string[] returnPhrase;public string query;/// <summary>/// 错误返回码/// </summary>public string errorCode;/// <summary>/// 源语言和目标语言/// </summary>public string l;/// <summary>/// 翻译结果发音地址/// </summary>public string tSpeakUrl;/// <summary>/// 网络释义 不一定存在/// </summary>public Web[] web;public string requestId;/// <summary>/// 翻译结果/// </summary>public string[] translation;public URL dict;public URL webdict;/// <summary>/// 词义/// </summary>public Basic basic;public bool isWord;/// <summary>/// 源语言发音地址/// </summary>public string speakUrl;
}
[Serializable]
public class Web
{public string key;public string[] value;
}
[Serializable]
public class URL
{public string url;
}
[Serializable]
public class Basic
{public string phonetic;public string[] explains;
}
封装接口:
public class YoudaoTranslator
{//应用ID和应用秘钥 通过在平台创建应用获取private static readonly string appKey = "**********";private static readonly string appSecret = "********************";/// <summary>/// 将英文翻译为中文/// </summary>/// <param name="content">待翻译的文本</param>/// <param name="callback">回调函数</param>public static void EnglishToChinese(string content, Action<string> callback){Translate(content, "en", "zh-CHS", callback);}/// <summary>/// 将中文翻译为英文/// </summary>/// <param name="content">待翻译的文本</param>/// <param name="callback">回调函数</param>public static void ChineseToEnglish(string content, Action<string> callback){Translate(content, "zh-CHS", "en", callback);}/// <summary>/// 翻译/// 中文zh-CHS 英文en 日文ja 韩文ko 法文fr 德文de 俄文ru/// 其它语言查阅官方文档/// </summary>/// <param name="content">待翻译的文本</param>/// <param name="from">源语言</param>/// <param name="to">目标语言</param>/// <param name="callback">回调函数</param>public static void Translate(string content, string from, string to, Action<string> callback){HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://openapi.youdao.com/api");request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";//当前UTC时间戳(秒)string curtime = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds / 1000).ToString();//UUID 唯一通用识别码string salt = DateTime.Now.Millisecond.ToString();string input = content == null ? null : content.Length <= 20 ? content : (content.Substring(0, 10) + content.Length + content.Substring(content.Length - 10, 10));byte[] inputBytes = Encoding.UTF8.GetBytes(appKey + input + salt + curtime + appSecret);byte[] hashedBytes = new SHA256CryptoServiceProvider().ComputeHash(inputBytes);//签名 sha256(应用ID + input + salt + curtime + 应用秘钥)//其中input的计算方式为:input=content前10个字符 + content长度 + cotent后10个字符(当cotent长度大于20)或 input=content字符串(当content长度小于等于20)string sign = BitConverter.ToString(hashedBytes).Replace("-", "");//签名类型string signType = "v3";//参数列表string args = string.Format("from={0}&to={1}&signType={2}&curtime={3}&q={4}&appKey={5}&salt={6}&sign={7}",from, to, signType, curtime, content, appKey, salt, sign);byte[] data = Encoding.UTF8.GetBytes(args);request.ContentLength = data.Length;using (Stream reqStream = request.GetRequestStream()){reqStream.Write(data, 0, data.Length);reqStream.Close();}HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();Stream stream = httpWebResponse.GetResponseStream();using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)){string responseStr = reader.ReadToEnd();//Debug.Log(responseStr);//反序列化var response = JsonUtility.FromJson<Response>(responseStr);int errorCode = int.Parse(response.errorCode);switch (errorCode){case 0: if (response.translation.Length > 0) callback.Invoke(response.translation[0]); break;case 102: Debug.LogError($"不支持的语言类型"); break;case 103: Debug.LogError($"翻译文本过长"); break;case 108: Debug.LogError($"应用ID无效 注册账号登录后台创建应用和实例并完成绑定 可获得应用ID和应用密钥等信息"); break;case 113: Debug.LogError($"待翻译文本不能为空"); break;//其它错误代码含义查阅官方文档default: Debug.LogError($"翻译失败 错误代码[{errorCode}]"); break;}}}
}
测试:
public class Foo : MonoBehaviour
{private void Start(){YoudaoTranslator.EnglishToChinese("Hello everyone.", s => Debug.Log(s));YoudaoTranslator.ChineseToEnglish("测试", s => Debug.Log(s));}
}