///////////////////////////////
// 小恐龙工作室
// https://xkonglong.com
///////////////////////////////////
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Trans_resultItem
{
public string src { get; set; }
public string dst { get; set; }
}
public class Root
{
public string @from { get; set; }
public string to { get; set; }
public List<Trans_resultItem> trans_result { get; set; }
}
public class Baidu
{
public string BaiduTrans(string text)
{
// 原文
string q = text;
// 源语言
string from = "auto";
// 目标语言
string to = "zh";
// 改成您的 your APP ID
string appId = "";
Random rd = new Random();
string salt = rd.Next(100000).ToString();
// 改成您的密钥 your key
string secretKey = "";
string sign = EncryptString(appId + q + salt + secretKey);
string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
url += "q=" + WebUtility.HtmlEncode(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();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
// 计算MD5值
public 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();
}
}
public static class ClipboardFusionHelper
{
public static string ProcessText(string text)
{
Baidu AB = new Baidu();
string retString = AB.BaiduTrans(text);
if (!retString.Contains("dst"))
{
BFS.Dialog.ShowTrayMessage("Error:获取翻译失败!");
}
else
{
Root rt = JsonConvert.DeserializeObject<Root>(retString);
for (int i = 0; i < rt.trans_result.Count; i++)
{
text=rt.trans_result[i].dst;
}
}
return text;
}
}