ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Unity 接入有道翻译接口API

2021-11-06 09:03:24  阅读:180  来源: 互联网

标签:break 翻译 string 有道 content Unity API Debug public


        接入接口前首先需要申请应用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));
    }
}

你学废(hui)了吗

 欢迎关注公众号 “当代野生程序猿”

标签:break,翻译,string,有道,content,Unity,API,Debug,public
来源: https://blog.csdn.net/qq_42139931/article/details/121174139

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有