public class Rootobject { public string from { get; set; } public string to { get; set; } public string domain { get; set; } public int type { get; set; } public int status { get; set; } public int error { get; set; } public string msg { get; set; } public Trans_Result[] trans_result { get; set; } } public class Trans_Result { public string src { get; set; } public string dst { get; set; } public int prefixWrap { get; set; } public object[] relation { get; set; } public object[][] result { get; set; } }
public static async Task<Rootobject> Baidu_Translate(string content) { return await Baidu_Translate("en", "zh", content); } public static async Task<Rootobject> Baidu_Translate(string from, string to, string content) { // 原文 string q = content; // 源语言 // 改成您的APP ID string appId = ""; Random rd = new Random(); string salt = rd.Next(100000).ToString(); // 改成您的密钥 string secretKey = ""; string sign = EncryptString(appId + q + salt + secretKey); string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?"; url += "q=" + HttpUtility.UrlEncode(q); url += "&from=" + from; url += "&to=" + to; url += "&appid=" + appId; url += "&salt=" + salt; url += "&sign=" + sign; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.UserAgent = null; request.Timeout = 6000; using (WebResponse response = await request.GetResponseAsync()) { using (Stream myResponseStream = response.GetResponseStream()) { using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"))) { string retString = myStreamReader.ReadToEnd(); Debug.WriteLine(retString); var result = JsonConvert.DeserializeObject<Rootobject>(retString); return result; } } } } // 计算MD5值 public static string EncryptString(string str) { MD5 md5 = MD5.Create(); // 将字符串转换成字节数组 byte[] byteOld = Encoding.UTF8.GetBytes(str); // 调用加密方法 byte[] byteNew = md5.ComputeHash(byteOld); // 将加密结果转换为字符串 StringBuilder sb = new StringBuilder(); foreach (byte b in byteNew) { // 将字节转换成16进制表示的字符串, sb.Append(b.ToString("x2")); } // 返回加密的字符串 return sb.ToString(); } private async void button1_Click(object sender, EventArgs e) { var res = await Baidu_Translate(richTextBox1.Text); string result = res.trans_result[0].dst; richTextBox2.Text = result; }
欢迎转载,转载请注明出处:http://www.cnblogs.com/Tonyyang/