https://www.songshizhao.com/blog/blogPage/1004.html
定义baidu返回的json对应的类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
namespace EasyNote.Translate.Baidu{ 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; } }} |
调用方法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
public static async Task<EasyNote.Translate.Baidu.Rootobject> Baidu_Translate(string from, string to, string content){ // 原文 string q = content; // 源语言 // 改成您的APP ID string appId = "<span style="font-size:15.3333px;white-space:normal;">这个需要前往百度翻译平台注册获取自己的ID</span>"; Random rd = new Random(); string salt = rd.Next(100000).ToString(); // 改成您的密钥 string secretKey = "百度翻译平台获取"; string sign = EncryptString(appId + q + salt + secretKey); 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; //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 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<EasyNote.Translate.Baidu.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();} |
百度翻译平台:http://api.fanyi.baidu.com/api/trans/product/apidoc
使用:
|
1
|
var res = await Translater.Baidu_Translate(MySettings.Baidu_From, MySettings.Baidu_To,redit.Document.Selection.Text); |
res.dst是翻译的结果
原文:https://www.cnblogs.com/Leo_wl/p/12495050.html