• C# 谷歌翻译API


         /// <summary>
            /// 谷歌翻译
            /// 
            /// 待翻译文本
            /// 自动检测:auto
            /// 中文:zh-CN,英文:en
            /// 翻译后文本
            /// </summary>
            /// <param name="text">待翻译文本</param>
            /// <param name="fromLanguage">自动检测:auto</param>
            /// <param name="toLanguage">中文:zh-CN,英文:en</param>
            /// <returns></returns>
            [HttpPost]
            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 TKK = re.Match(BaseResultHtml).ToString();//在返回的HTML中正则匹配TKK的值
                
                string path = Server.MapPath("~/");//获取路径
    
                string jspath = path + "/content/js/gettk.js";
    
                var GetTkkJS = System.IO.File.ReadAllText(jspath);
    
                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, "https://translate.google.cn/");
    
                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 refer)
            {
                var html = "";
    
                var webRequest = WebRequest.Create(url) as HttpWebRequest;
    
                webRequest.Method = "GET";
    
                webRequest.CookieContainer = cookie;
    
                webRequest.Referer = refer;
    
                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/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
    
                using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                    {
    
                        html = reader.ReadToEnd();
                        reader.Close();
                        webResponse.Close();
                    }
                }
                return html;
            }
    
    
            /// 执行JS
            /// 
            /// 参数体
            /// JavaScript代码的字符串
            /// 
            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;
            }
    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)
    }

    程序中有小改动

    参考文章:https://www.cnblogs.com/marso/p/google_translate_api.html

    线上可能出现一下问题:

    请求这个方法异常:

    Exception type: COMException
    Exception message: 检索 COM 类工厂中 CLSID 为 {0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC} 的组件失败,原因是出现以下错误: 80040154 没有注册类 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG))

    解决办法:

    IIS7的话。在应用程序池的高级设置中,启用32位应用程序。

    经过测试此方法有效

    解决办法参考:https://blog.csdn.net/bianjing40/article/details/53419251

  • 相关阅读:
    Android 中设置全屏和无标题模式
    轻松管理安卓应用中的log打印信息
    使用Cocos2d游戏引擎开发火热的植物大战僵尸游戏
    Android中获取系统通讯录联系人并显示在EditText
    使用json解析国家气象局(天气预报)接口数据
    Android中简单的日期格式化
    Android的消息推送技术Androidpn
    格式化日期和时间详细介绍
    智能短信管家 V1.0版本正式上线啦!
    学用MVC4做网站一:用户登陆1.2
  • 原文地址:https://www.cnblogs.com/dyd520/p/13853761.html
Copyright © 2020-2023  润新知