C#&.Net干货分享- 构造BaiduLanguageHelper对接百度的语言翻译

全部是封装的API源码。。。

namespace Frame.Api
{
    /// <summary>
    /// 百度多语言支持器
    /// </summary>
    public class BaiduLanguageHelper
    {
        /*
语言简写    名称
auto    自动检测
zh    中文
en    英语
yue    粤语
wyw    文言文
jp    日语
kor    韩语
fra    法语
spa    西班牙语
th    泰语
ara    阿拉伯语
ru    俄语
pt    葡萄牙语
de    德语
it    意大利语
el    希腊语
nl    荷兰语
pl    波兰语
bul    保加利亚语
est    爱沙尼亚语
dan    丹麦语
fin    芬兰语
cs    捷克语
rom    罗马尼亚语
slo    斯洛文尼亚语
swe    瑞典语
hu    匈牙利语
cht    繁体中文
vie    越南语
         */

        //可以直接到百度翻译API的官网申请
        private static string LAN_APPID_BAI_DU = WebConfigHelper.GetWebConfigString("BaiduLanAppId");

        //可以直接到百度翻译API的官网申请
        private static string LAN_PWD_BAI_DU = WebConfigHelper.GetWebConfigString("BaiduLanPwd");

        /// <summary>
        /// 调用百度翻译API进行翻译
        /// 详情可参考http://api.fanyi.baidu.com/api/trans/product/apidoc
        /// </summary>
        /// <param name="tContent">待翻译字符</param>
        /// <param name="fromLan">源语言</param>
        /// <param name="toLan">目标语言</param>
        /// <returns>翻译结果</returns>
        public static string Translation(string tContent, string fromLan, string toLan)
        {
            string jsonResult = String.Empty;
            string languageFrom = fromLan.ToLower();
            string languageTo = toLan.ToLower();
            string randomNum = System.DateTime.Now.Millisecond.ToString();
            string md5Sign = GetMD5WithString(LAN_APPID_BAI_DU + tContent + randomNum + LAN_PWD_BAI_DU);
            String url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}", HttpUtility.UrlEncode(tContent, Encoding.UTF8), languageFrom, languageTo, LAN_APPID_BAI_DU, randomNum, md5Sign);
            WebClient wc = new WebClient();
            try
            {
                jsonResult = wc.DownloadString(url);
            }
            catch
            {
                jsonResult = string.Empty;
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();
            TranslationResult ret = jss.Deserialize<TranslationResult>(jsonResult);
            if (ret != null && string.IsNullOrEmpty(ret.Error_code))
            {
                return ret.Trans_result[0].Dst.Trim();
            }
            //翻译失败,返回原来的字符
            return tContent;
        }


        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="input">待加密字符串</param>
        /// <returns>加密结果</returns>
        private static string GetMD5WithString(string input)
        {
            //input必须转换为UTF-8编码
            if (input == null)
            {
                return null;
            }
            MD5 md5Hash = MD5.Create();
            // 将输入字符串转换为字节数组并计算哈希数据  
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            // 创建一个 Stringbuilder 来收集字节并创建字符串  
            StringBuilder sBuilder = new StringBuilder();
            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // 返回十六进制字符串  
            return sBuilder.ToString();
        }

    }

    /// <summary>
    /// 翻译API返回对象
    /// </summary>
    public class TranslationResult
    {
        /// <summary>
        ///
        /// </summary>
        public string Error_code { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string Error_msg { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string From { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string To { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string Query { get; set; }

        /// <summary>
        ///
        /// </summary>
        public Translation[] Trans_result { get; set; }
    }

    /// <summary>
    ///
    /// </summary>
    public class Translation
    {
        /// <summary>
        ///
        /// </summary>
        public string Src { get; set; }

        /// <summary>
        ///
        /// </summary>
        public string Dst { get; set; }
    }
}

posted @ 2019-09-04 11:39  滑溜溜的小热浪  阅读(337)  评论(0编辑  收藏  举报