The latest C# calls Google Instant Translate

It is mainly to call Google's translation api for translation, WebRequest request, and extract the obtained translation. code below

You need to use a Js file: filter the acquired data, named gettk.js

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)
}


Front desk code:

<Window x:Class="Translate.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Google翻译" Height="439" Width="525" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.Background>
            <ImageBrush ImageSource="t012abd86418d9b50f9.jpg"/>
        </Grid.Background>
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" FontSize="14" Name="textBlock1" Text="输入单词:" VerticalAlignment="Top"/>
        <TextBox Foreground="Red" FontSize="14" Background="Transparent" Height="94" HorizontalAlignment="Left" Margin="10,40,0,0" Name="txtWord" VerticalAlignment="Top" Width="487" TextChanged="txtWord_TextChanged"/>
        <TextBox  Foreground="Red" FontSize="14" Background="Transparent"  Height="242" HorizontalAlignment="Left" Margin="10,157,0,0" Name="txtResult" VerticalAlignment="Top" Width="487" />
    </Grid>
</Window>

Background code: need to add MSScriptControl reference, parse Js file

#region method

        /// <summary>Regular check
        /// </summary>
        /// <param name="str"></param>
        /// <param name="matchStr">正则</param>
        /// <returns></returns>
        public static bool ValidateStr(string str, string matchStr)
        {
            try
            {
                return System.Text.RegularExpressions.Regex.IsMatch(str, matchStr);
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <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.cn/";

            var BaseResultHtml = GetResultHtml(GoogleTransBaseUrl, cc, "");

            Regex re = new Regex(@"(?<=TKK=)(.*?)(?=\);)");

            var TKKStr = re.Match(BaseResultHtml).ToString() + ")";//Regularly match the JS code of TKK in the returned HTML

            var TKK = ExecuteScript(TKKStr, TKKStr);//Execute the TKK code to get the TKK value

            var GetTkkJS = File.ReadAllText(@"gettk.js");

            var tk = ExecuteScript("tk(\"" + text + "\",\"" + TKK + "\")", GetTkkJS);

            string googleTransUrl = "https://translate.google.cn/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, "");

            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 = url;//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">String of JavaScript code</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;
        }
        #endregion

Interface rendering:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325411847&siteId=291194637