接入接口前首先需要申请应用ID和应用秘钥,登录有道智云AI开放平台,创建应用,获取应用ID和秘钥。
定义接口响应类数据结构,接口实际返回内容和官方文档有点出入,大概是文档未更新吧。
以下是官方文档给出的说明:
以下是本人测试获取到的响应结构:
定义该数据结构:
[Serializable] publicclassResponse{ /// <summary>/// 单词校验后的结果 主要校验字母大小写、单词前含符号、中文简繁体/// </summary>publicstring[] returnPhrase; publicstringquery; /// <summary>/// 错误返回码/// </summary>publicstringerrorCode; /// <summary>/// 源语言和目标语言/// </summary>publicstringl; /// <summary>/// 翻译结果发音地址/// </summary>publicstringtSpeakUrl; /// <summary>/// 网络释义 不一定存在/// </summary>publicWeb[] web; publicstringrequestId; /// <summary>/// 翻译结果/// </summary>publicstring[] translation; publicURLdict; publicURLwebdict; /// <summary>/// 词义/// </summary>publicBasicbasic; publicboolisWord; /// <summary>/// 源语言发音地址/// </summary>publicstringspeakUrl; } [Serializable] publicclassWeb{ publicstringkey; publicstring[] value; } [Serializable] publicclassURL{ publicstringurl; } [Serializable] publicclassBasic{ publicstringphonetic; publicstring[] explains; }
封装接口:
publicclassYoudaoTranslator{ //应用ID和应用秘钥 通过在平台创建应用获取privatestaticreadonlystringappKey="**********"; privatestaticreadonlystringappSecret="********************"; /// <summary>/// 将英文翻译为中文/// </summary>/// <param name="content">待翻译的文本</param>/// <param name="callback">回调函数</param>publicstaticvoidEnglishToChinese(stringcontent, Action<string>callback) { Translate(content, "en", "zh-CHS", callback); } /// <summary>/// 将中文翻译为英文/// </summary>/// <param name="content">待翻译的文本</param>/// <param name="callback">回调函数</param>publicstaticvoidChineseToEnglish(stringcontent, 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>publicstaticvoidTranslate(stringcontent, stringfrom, stringto, Action<string>callback) { HttpWebRequestrequest= (HttpWebRequest)WebRequest.Create("https://openapi.youdao.com/api"); request.Method="POST"; request.ContentType="application/x-www-form-urlencoded"; //当前UTC时间戳(秒)stringcurtime= ((long)(DateTime.UtcNow-newDateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds/1000).ToString(); //UUID 唯一通用识别码stringsalt=DateTime.Now.Millisecond.ToString(); stringinput=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=newSHA256CryptoServiceProvider().ComputeHash(inputBytes); //签名 sha256(应用ID + input + salt + curtime + 应用秘钥)//其中input的计算方式为:input=content前10个字符 + content长度 + cotent后10个字符(当cotent长度大于20)或 input=content字符串(当content长度小于等于20)stringsign=BitConverter.ToString(hashedBytes).Replace("-", ""); //签名类型stringsignType="v3"; //参数列表stringargs=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 (StreamreqStream=request.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponsehttpWebResponse= (HttpWebResponse)request.GetResponse(); Streamstream=httpWebResponse.GetResponseStream(); using (StreamReaderreader=newStreamReader(stream, Encoding.UTF8)) { stringresponseStr=reader.ReadToEnd(); //Debug.Log(responseStr);//反序列化varresponse=JsonUtility.FromJson<Response>(responseStr); interrorCode=int.Parse(response.errorCode); switch (errorCode) { case0: if (response.translation.Length>0) callback.Invoke(response.translation[0]); break; case102: Debug.LogError($"不支持的语言类型"); break; case103: Debug.LogError($"翻译文本过长"); break; case108: Debug.LogError($"应用ID无效 注册账号登录后台创建应用和实例并完成绑定 可获得应用ID和应用密钥等信息"); break; case113: Debug.LogError($"待翻译文本不能为空"); break; //其它错误代码含义查阅官方文档default: Debug.LogError($"翻译失败 错误代码[{errorCode}]"); break; } } } }
测试:
publicclassFoo : MonoBehaviour{ privatevoidStart() { YoudaoTranslator.EnglishToChinese("Hello everyone.", s=>Debug.Log(s)); YoudaoTranslator.ChineseToEnglish("测试", s=>Debug.Log(s)); } }