2.Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Win { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using DevExpress.ExpressApp.Utils; public class MyTranslatorProvider : TranslatorProviderBase { private const int timeout = 15000; public string appId = "65C7264047E3D58C91A7655FCD8F5E6892306B1B"; private const string serviceUrl = "http://api.microsofttranslator.com/V1/Http.svc/"; private string[] languages; public override string Caption => "Microsoft MyTranslator"; public override string Description => "Powered by <b>Microsoft® MyTranslator</b>"; public MyTranslatorProvider() : base("<br>", 2000) { languages = null; } private string BingTranslatorInvoke(string methodName, IEnumerable<KeyValuePair<string, string>> parameters) { return BingTranslatorInvoke(methodName, parameters, null); } /// <summary> /// /// </summary> /// <param name="methodName"></param> /// <param name="parameters"></param> /// <param name="postParameter"></param> /// <returns></returns> private string BingTranslatorInvoke(string methodName, IEnumerable<KeyValuePair<string, string>> parameters, string postParameter) { string text2 = null; if (methodName == "Detect") { text2 = "en"; } else if (methodName == "Translate") { text2 = BaiduTranslate.Baidu_Translate(postParameter).trans_result[0].dst; } else if (methodName == "GetLanguages") { } return text2; } private string BingTranslatorInvoke2(string methodName, IEnumerable<KeyValuePair<string, string>> parameters, string postParameter) { UTF8Encoding encoding = new UTF8Encoding(); string text = ""; foreach (KeyValuePair<string, string> parameter in parameters) { text += (string.IsNullOrEmpty(text) ? "?" : "&"); text = text + parameter.Key + "=" + parameter.Value; } Uri requestUri = new Uri("http://api.microsofttranslator.com/V1/Http.svc/" + methodName + text); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri); httpWebRequest.Timeout = 15000; if (!string.IsNullOrEmpty(postParameter)) { httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "text/plain"; Stream stream = httpWebRequest.GetRequestStream(); byte[] bytes = Encoding.UTF8.GetBytes(postParameter); stream.Write(bytes, 0, bytes.Length); } HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); string text2 = null; StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), encoding); text2 = streamReader.ReadToEnd(); return text2; } public override string[] GetLanguages() { if (languages == null) { languages = "zh-CHS,en".Split(','); //string text = BingTranslatorInvoke("GetLanguages", new KeyValuePair<string, string>[1] //{ //new KeyValuePair<string, string>("appId", appId) //}); //languages = text.Split(new string[1] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } return languages; } public string Detect(string text) { return BingTranslatorInvoke("Detect", new KeyValuePair<string, string>[1] { new KeyValuePair<string, string>("appId", appId) }, text); } public override string Translate(string text, string sourceLanguageCode, string destinationLanguageCode) { if (string.IsNullOrEmpty(sourceLanguageCode)) { sourceLanguageCode = Detect(text); } return BingTranslatorInvoke("Translate", new KeyValuePair<string, string>[3] { new KeyValuePair<string, string>("appId", appId), new KeyValuePair<string, string>("from", sourceLanguageCode), new KeyValuePair<string, string>("to", destinationLanguageCode) }, text); } public override IEnumerable<string> CalculateSentences(string text) { string[] leftSeparators = new string[5] { "\"", "^'", " '", "('", "{" }; string[] rightSeparators = new string[5] { "\"", "'", "'", "'", "}" }; int num = 0; int iSeparator = 0; int leftSeparatorSize = 0; while (num < text.Length) { int num2 = -1; for (int i = 0; i < leftSeparators.Length; i++) { if (leftSeparators[i][0] == '^') { int num3 = text.IndexOf(leftSeparators[i].Substring(1), num, StringComparison.Ordinal); if (num3 == 0) { iSeparator = i; num2 = num3; leftSeparatorSize = leftSeparators[i].Length - 1; } } else { int num3 = text.IndexOf(leftSeparators[i], num, StringComparison.Ordinal); if (num3 >= 0 && (num2 < 0 || num3 < num2)) { iSeparator = i; num2 = num3; leftSeparatorSize = leftSeparators[i].Length; } } } if (num2 >= 0) { int rightSeparatorIndex = text.IndexOf(rightSeparators[iSeparator], num2 + leftSeparatorSize, StringComparison.Ordinal); if (rightSeparatorIndex >= 0) { string text2 = text.Substring(num, num2 - num).Trim(); if (text2.Length > 0) { yield return text2; } num = rightSeparatorIndex + rightSeparators[iSeparator].Length; continue; } } yield return text.Substring(num, text.Length - num).Trim(); num = text.Length; } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web; namespace Common.Win { public class BaiduTranslate { public static Rootobject Baidu_Translate(string content) { return Baidu_Translate("en", "zh", content); } public static Rootobject Baidu_Translate(string from, string to, string content) { // 原文 string q = content; // 源语言 // 改成您的APP ID string appId = "";//to do Random rd = new Random(); string salt = rd.Next(100000).ToString(); // 改成您的密钥 string secretKey = "";//to do string sign = EncryptString(appId + q + salt + secretKey); string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";//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 = request.GetResponse()) { 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(); } } 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; } } }
3.百度开发者中心百度翻译开放平台 (baidu.com)
欢迎转载,转载请注明出处:http://www.cnblogs.com/Tonyyang/