Since the Google Translate official API is a paid version, in the spirit of free and open source, share the code to implement the Google Translate API with C#. This code is very simple, mainly divided into two parts: request content through WebRequest; get the request parameters of Get mode (the difficulty lies in the acquisition of tk). Note that the project needs to add the following references:

System.Web

Newtonsoft.Json

MSScriptControl (Microsoft Script Control 1.0 in the com component)

First, the 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();
   }
  }

Second, the realization of Google’s translation interface

  1. Capture the package and view the translation network request. Here is the network request viewed by Google Chrome, as shown below:

As you can see, the request method is “Get” mode, followed by a lot of request parameters, as shown below:

Among them, the most important parameters are: sl–source language, generally set to auto is automatic detection, tl–target language, the language you want to translate, tk–ticket even if the ticket is issued, Google relies on this to prevent us Called for free, this is the hardest part of this API.

  2, the acquisition of tk

  In the open https://translate.google.com/ page, the obtained HTML code has the following value of TKK:

Match this value directly with the regular source code: Regex re = new Regex(@”(?<=TKK=’)(.*?)(?=’)”), you can get a string: 428502.368022592

 

  From the monitored network, you can find that one of the JS calls this TKK value. This JS is encrypted and confused. To solve this JS requires solid basic skills and patience. I am also looking for someone to crack the JS code on the Internet. Pro test is available, you need to save this code in the gettk.js document, which is convenient to call:

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 get tk only, run the tk function, which has two input values: a is the translated text content, and TKK is the result of the JS string execution obtained by the above regular match. To facilitate the execution of JS in C#, a function that can execute JS is encapsulated, as follows:

/// <summary>
/// Execute JS
/// </summary>
/// <param name="sExpression"></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, the complete code to achieve translation

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using MSScriptControl;
using System.Web;
 
namespace GoogleTranslate
{
    public class Translate
    {
        /// <summary>
        /// google translate
        /// </summary>
        /// <param name="text">text to be translated</param>
        /// <param name="fromLanguage">auto detect:auto</param>
        /// <param name="toLanguage">Chinese:zh-CN,English:en</param>
        /// <returns>text translated</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 TKK = re.Match(BaseResultHtml).ToString();//get TKK from HTML
 
            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 cookie, string referer)
        {
            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 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
 
            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"></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;
        }
    }
}