C # implement Google Translate API,

Source: Internet
Author: User
Tags webp

C # implement Google Translate API,

Since Google Translate's official API is a paid version, in the spirit of free and open source, share the code for implementing Google Translate API with C. This code is very simple, mainly divided into two parts: request content through WebRequest; Get request parameters (the difficulty lies in obtaining tk ).

1. WebRequest code

var webRequest = WebRequest.Create(url) as HttpWebRequest;webRequest.Method = "GET";webRequest.CookieContainer = cookie;webRequest.Referer = referer;webRequest.Timeout = 20000;webRequest.Headers.Add("X-Requested-With:XMLHttpRequest");webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";webRequest.UserAgent = useragent;  using (var webResponse = (HttpWebResponse)webRequest.GetResponse())  {   using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))   {    html = reader.ReadToEnd();    reader.Close();    webResponse.Close();   }  }

  

2. Implementation of Google translation Interfaces

1. Capture packets to view translation network requests. Here, we use Google Chrome to view network requests, for example:

 

 

We can see that the request method is "Get", followed by many request parameters, such:

Among them, the most important parameters are: sl-source language, which is generally set to auto for automatic detection, tl-target language, the language you want to translate into, tk-ticket even if the departure ticket, google relies on this to prevent free calls, which is the most difficult part of this API.

2. Obtain tk

On the https://translate.google.com/page, the obtained HTML code contains the script that generates tkk:

 

Run this script directly to generate a string:

From the monitoring network, we can find that one of the JS calls this TKK value. This JS is obfuscated by the secret. to crack this JS requires solid basic skills and patience, I am also looking for someone else to crack the JS Code on the Internet. It is available for test. You need to save this code inGettk. jsDocumentation for convenient calls:

var b = function (a, b) {    for (var d = 0; d < b.length - 2; d += 3) {        var c = b.charAt(d + 2),            c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),            c = "+" == b.charAt(d + 1) ? a >>> c : a << c;        a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c    }    return a}var tk =  function (a,TKK) {    for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {        var c = a.charCodeAt(f);        128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)    }    a = h;    for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");    a = b(a, "+-3^+b+-f");    a ^= Number(e[1]) || 0;    0 > a && (a = (a & 2147483647) + 2147483648);    a %= 1E6;    return a.toString() + "." + (a ^ h)}

  

To obtain tk, you only need to run the tk function. It has two input values: a is the content of the translated text, and TKK is the result value of JS string execution obtained by regular match above. To facilitate JS execution in C #, a function that can execute JS is encapsulated as follows:

/// <Summary> /// execute JS /// </summary> /// <param name = "sExpression"> parameter body </param> /// <param name = "sCode"> JavaScript code string </param> // <returns> </returns> private string ExecuteScript (string sExpression, string sCode) {MSScriptControl. scriptControl scriptControl = new MSScriptControl. scriptControl (); scriptControl. useSafeSubset = true; scriptControl. language = "JScript"; scriptControl. addCode (sCode); try {string str = scriptControl. eval (sExpression ). toString (); return str;} catch (Exception ex) {string str = ex. message;} return null ;}

  

3. complete translation code

/// <Summary> /// Google Translate /// </summary> /// <param name = "text"> text to be translated </param> /// <param name = "fromLanguage"> Automatic Detection: auto </param> /// <param name = "toLanguage"> Chinese: zh-CN, English: en </param> // <returns> translated text </returns> public string GoogleTranslate (string text, string fromLanguage, string toLanguage) {CookieContainer cc = new CookieContainer (); string GoogleTransBaseUrl =" https://translate.google.com/ "; Var BaseResultHtml = GetResultHtml (GoogleTransBaseUrl, cc," "); Regex re = new Regex (@"(? <= TKK = )(.*?) (? = \);) "); Var TKKStr = re. match (BaseResultHtml ). toString () + ")"; // matches the JS Code var TKK = ExecuteScript (TKKStr, TKKStr) of TKK in the returned HTML; // executes the TKK code, get the TKK value var GetTkkJS = File. readAllText (". /gettk. js "); var tk = ExecuteScript (" tk (\ "" + text + "\", \ "" + TKK + "\") ", GetTkkJS ); string googleTransUrl =" https://translate.google.com/ Translate_a/single? Client = t & sl = "+ fromLanguage +" & tl = "+ toLanguage +" & hl = en & dt = at & dt = bd & dt = ex & dt = ld & dt = md & dt = qca & dt = rw & dt = rm & dt = ss & dt = t & ie = UTF-8 & oe = UTF-8 & otf = 1 & ssel = 0 & tsel = 0 & kc = 1 & tk = "+ tk +" & q = "+ HttpUtility. urlEncode (text); var ResultHtml = GetResultHtml (googleTransUrl, cc ," https://translate.google.com/ "); Dynamic TempResult = Newtonsoft. json. jsonConvert. deserializeObject (ResultHtml); string ResultText = Convert. toString (TempResult [0] [0] [0]); return ResultText;} public string GetResultHtml (string url, CookieContainer cc, string refer) {var html = ""; var webRequest = WebRequest. create (url) as HttpWebRequest; webRequest. method = "GET"; webRequest. cookieContainer = cookie; webRequest. referer = referer; webRequest. timeout = 20000; webRequest. headers. add ("X-Requested-With: XMLHttpRequest"); webRequest. accept = "text/html, application/xhtml + xml, application/xml; q = 0.9, image/webp, */*; q = 0.8"; webRequest. userAgent = useragent; using (var webResponse = (HttpWebResponse) webRequest. getResponse () {using (var reader = new StreamReader (webResponse. getResponseStream (), Encoding. UTF8) {html = reader. readToEnd (); reader. close (); webResponse. close () ;}} return html ;} /// <summary> /// execute JS /// </summary> /// <param name = "sExpression"> parameter body </param> /// <param name = "sCode"> JavaScript code string </param> // <returns> </returns> private string ExecuteScript (string sExpression, string sCode) {MSScriptControl. scriptControl scriptControl = new MSScriptControl. scriptControl (); scriptControl. useSafeSubset = true; scriptControl. language = "JScript"; scriptControl. addCode (sCode); try {string str = scriptControl. eval (sExpression ). toString (); return str;} catch (Exception ex) {string str = ex. message;} return null ;}

  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.