码迷,mamicode.com
首页 > 其他好文 > 详细

百度翻译

时间:2017-06-06 14:24:01      阅读:1063      评论:0      收藏:0      [点我收藏+]

标签:lis   sre   decode   http   fan   code   returns   serialize   salt   

/// <summary>
    /// 百度翻译
    /// </summary>
    public class BaiDuTransHelp
    {
        /// <summary>
        /// 密钥
        /// </summary>
        private readonly static string TransKey = ConfigurationManager.AppSettings["TransKey"];

        /// <summary>
        /// App ID
        /// </summary>
        private readonly static string AppID = ConfigurationManager.AppSettings["AppID"];

        /// <summary>
        /// 翻译
        /// </summary>
        /// <param name="query"></param>
        /// <param name="toLan">zh:中文,en:英语,cht:繁体中文</param>
        /// <returns></returns>
        public static string Trans(string query, string toLan)
        {
            WebClient client = new WebClient();
            Random rd = new Random();
            string rdNum = rd.Next(1000).ToString();

            string sign = AppID + GetUTF8Str(query) + rdNum + TransKey;

            sign = MD5.Md5Hash(sign);

            string url = string.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from=auto&to={1}&appid={2}&salt={3}&sign={4}",
                HttpUtility.UrlEncode(query), HttpUtility.UrlEncode(toLan), HttpUtility.UrlEncode(AppID), HttpUtility.UrlEncode(rdNum), HttpUtility.UrlEncode(sign));
            var buffer = client.DownloadData(url);
            string result = Encoding.UTF8.GetString(buffer);
            StringReader sr = new StringReader(result);
            JsonTextReader jsonReader = new JsonTextReader(sr);
            JsonSerializer serializer = new JsonSerializer();
            var r = serializer.Deserialize<TransObj>(jsonReader);
            string toStr = string.Empty;
            if (r.trans_result != null)
            {
                toStr = r.trans_result[0].dst;
            }
            return toStr;
        }

        /// <summary>
        /// 获取Utf-8编码字符串
        /// </summary>
        /// <param name="unicodeString"></param>
        /// <returns></returns>
        public static string GetUTF8Str(string unicodeString)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(unicodeString);
            String decodedString = utf8.GetString(encodedBytes);
            return decodedString;
        }

        private class TransObj
        {
            public string from { get; set; }
            public string to { get; set; }
            public List<TransResult> trans_result { get; set; }
        }

        private class TransResult
        {
            public string src { get; set; }
            public string dst { get; set; }
        }
    }

 

百度翻译

标签:lis   sre   decode   http   fan   code   returns   serialize   salt   

原文地址:http://www.cnblogs.com/tangchun/p/6950909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!