1. 程式人生 > >Net Core 實現谷歌翻譯ApI 免費版

Net Core 實現谷歌翻譯ApI 免費版

display rst 助手 dto 獲取 ice image htm bsp

原文:Net Core 實現谷歌翻譯ApI 免費版

  由於谷歌翻譯官方API是付費版本,本著免費和開源的精神。分享一下用 Net Core 實現谷歌翻譯API的代碼。

項目引用的Nuget 包:

ChakraCore.NET

Newtonsoft.Json

JavaScriptEngineSwitcher.ChakraCore.Native.win-x86(特別說明一下"win-x86",代表程序運行環境。)

翻譯地址:https://translate.google.cn (國內可以訪問)

參數說明

text:待翻譯文本

sl:需要翻譯的語言(中文:zh-CN,英文:en)

tl: 翻譯結果的語言(中文:zh-CN,英文:en)

技術分享圖片

技術分享圖片
 1 public class HttpHelper
 2     {
 3         /// <summary>
 4         /// 請求
 5         /// </summary>
 6         /// <param name="url">地址</param>
 7         /// <param name="args">參數</param>
 8         /// <returns></returns>
9 public static string GetRequest(string url, CookieContainer cookieContainer, Dictionary<string, dynamic> args) 10 { 11 try 12 { 13 if (args.Count > 0) 14 { 15 var argStr = string.Empty; 16 17
foreach (var item in args) 18 { 19 if (item.Key == null || item.Value == null) 20 { 21 continue; 22 } 23 argStr = $"{argStr}{item.Key}={item.Value}&"; 24 } 25 26 url = $"{url}?{argStr.TrimEnd(‘&‘)}"; 27 } 28 29 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 30 request.Method = "get"; 31 request.Timeout = 100000; 32 request.CookieContainer = cookieContainer; 33 request.UserAgent = GetUserAgent(); 34 request.Headers.Add("X-Requested-With:XMLHttpRequest"); 35 request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; 36 using (var webResponse = (HttpWebResponse)request.GetResponse()) 37 { 38 using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) 39 { 40 41 return reader.ReadToEnd(); 42 } 43 } 44 } 45 catch (Exception) 46 { 47 return string.Empty; 48 } 49 } 50 51 /// <summary> 52 /// 用戶代理 53 /// </summary> 54 /// <returns></returns> 55 private static string GetUserAgent() 56 { 57 var userAgents = new List<string> 58 { 59 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", 60 "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", 61 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", 62 "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", 63 "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", 64 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", 65 "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", 66 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", 67 "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", 68 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", 69 "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", 70 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", 71 "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", 72 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", 73 "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", 74 "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", 75 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", 76 "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", 77 "Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 ", 78 "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3", 79 "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5", 80 "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.14) Gecko/20110218 AlexaToolbar/alxf-2.0 Firefox/3.6.14", 81 "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15", 82 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1", 83 "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11", 84 "Opera/9.80 (Android 2.3.4; Linux; Opera mobi/adr-1107051709; U; zh-cn) Presto/2.8.149 Version/11.10", 85 "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10", 86 "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8", 87 "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5", 88 "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0", 89 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)", 90 "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)", 91 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" 92 }; 93 94 return userAgents.OrderBy(x => Guid.NewGuid()).First(); 95 } 96 }
HttpHelper

技術分享圖片
  1 /// <summary>
  2     /// 翻譯 助手
  3     /// </summary>
  4     public static class TranslationHelper
  5     {
  6         /// <summary>
  7         /// Chakra 上下文
  8         /// </summary>
  9         private static readonly ChakraContext _chakraContext;
 10 
 11         /// <summary>
 12         /// Cookie
 13         /// </summary>
 14         private static readonly CookieContainer _cookieContainer;
 15 
 16         /// <summary>
 17         /// 請求地址
 18         /// </summary>
 19         private static readonly string _baseUrl;
 20 
 21         /// <summary>
 22         /// 靜態
 23         /// </summary>
 24         static TranslationHelper()
 25         {
 26             var runtime = ChakraRuntime.Create();
 27 
 28             _baseUrl = "http://translate.google.cn/translate_a/single";
 29             _cookieContainer = new CookieContainer();
 30             _chakraContext = runtime.CreateContext(true);
 31 
 32             var basePath = PlatformServices.Default.Application.ApplicationBasePath;
 33             var jsFileText = File.ReadAllText($@"{basePath}\gettk.js");
 34 
 35             _chakraContext.RunScript(jsFileText); //運行腳本
 36         }
 37 
 38         /// <summary>
 39         /// 獲取翻譯結果(需要翻譯的文字默認使用中文)
 40         /// </summary>
 41         /// <param name="toLang">語言</param>
 42         /// <param name="originalText">待翻譯的文本</param>
 43         /// <returns></returns>
 44         public static string GetTranslation(this string toLang, string originalText)
 45         {
 46             if (string.IsNullOrEmpty(toLang))
 47             {
 48                 return toLang;
 49             }
 50             if (string.IsNullOrEmpty(originalText))
 51             {
 52                 return originalText;
 53             }
 54 
 55             return GetTranslation("zh-cn", toLang, originalText);
 56 
 57         }
 58 
 59         /// <summary>
 60         /// 獲取翻譯結果
 61         /// </summary>
 62         /// <param name="fromLang">需要翻譯的語言</param>
 63         /// <param name="toLang">翻譯結果的語言</param>
 64         /// <param name="originalText">待翻譯文本</param>
 65         /// <returns></returns>
 66         public static string GetTranslation(this string fromLang, string toLang, string originalText)
 67         {
 68             var args = new Dictionary<string, dynamic>
 69             {
 70                 { "client", "t" },
 71                 { "sl", fromLang },
 72                 { "tl", toLang },
 73                 { "dt", "t" },
 74                 { "tk", GetTK(originalText) },
 75                 { "text", HttpUtility.UrlEncode(originalText) }
 76             };
 77 
 78             var result = HttpHelper.GetRequest(_baseUrl, _cookieContainer, args);
 79 
 80             return result.FormattedJson();
 81         }
 82 
 83         /// <summary>
 84         /// 獲取TK
 85         /// </summary>
 86         /// <param name="originalText"></param>
 87         /// <returns></returns>
 88         private static string GetTK(string originalText)
 89         {
 90             _chakraContext.GlobalObject.WriteProperty("originalText", originalText);
 91             return _chakraContext.RunScript("getTK(originalText)");
 92         }
 93 
 94         /// <summary>
 95         /// 格式化Json
 96         /// </summary>
 97         /// <param name="jsonStr">Json</param>
 98         /// <returns></returns>
 99         private static string FormattedJson(this string jsonStr)
100         {
101             if (string.IsNullOrEmpty(jsonStr))
102             {
103                 return string.Empty;
104             }
105 
106             var array = JsonConvert.DeserializeObject<JArray>(jsonStr);
107 
108             var result = array[0][0][0].ToString();
109 
110             return result;
111         }
112 
113     }
TranslationHelper

參考:C#實現谷歌翻譯API

Net Core 實現谷歌翻譯ApI 免費版