首页 > 代码库 > 百度翻译
百度翻译
/// <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; } } }
百度翻译
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。