コード例 #1
0
        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }


            // 原文
            string q = sourceText;

            string retString;

            Random rd   = new Random();
            string salt = rd.Next(100000).ToString();

            string url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_texttranslate?";

            var sb = new StringBuilder()
                     .Append("app_id=").Append(appId)
                     .Append("&nonce_str=").Append(salt)
                     .Append("&source=").Append(srcLang)
                     .Append("&target=").Append(desLang)
                     .Append("&text=").Append(HttpUtility.UrlEncode(q).ToUpper())
                     .Append("&time_stamp=").Append(CommonFunction.GetTimeStamp());

            sb.Append("&sign=" + CommonFunction.EncryptString(sb.ToString() + "&app_key=" + appKey).ToUpper());
            string req = sb.ToString();

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = hc.GetStringAsync(url + req).GetAwaiter().GetResult();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            TencentTransOutInfo oinfo = JsonConvert.DeserializeObject <TencentTransOutInfo>(retString);

            if (oinfo.ret == "0")
            {
                //得到翻译结果
                return(oinfo.data.target_text);
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.ret + " ErrorInfo:" + oinfo.msg;
                return(null);
            }
        }
コード例 #2
0
        /// <summary>
        /// 访问页面
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cc"></param>
        /// <param name="refer"></param>
        /// <returns></returns>
        public string GetResultHtml(string url)
        {
            var hc = CommonFunction.GetHttpClient();

            return(hc.GetStringAsync(url).GetAwaiter().GetResult());

            // string usergant = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
            //webRequest.Referer = "https://translate.google.cn/";
            //webRequest.Headers.Add("X-Requested-With:XMLHttpRequest");
            //webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
        }
コード例 #3
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            string payload = "text=" + sourceText
                             + "&auth_key=" + secretKey
                             + "&source_lang=" + transformSrcLangKey(srcLang)
                             + "&target_lang=" + transformDesLangKey(desLang);

            StringContent request = new StringContent(payload, null, "application/x-www-form-urlencoded");

            try
            {
                HttpResponseMessage response = await CommonFunction.GetHttpClient().PostAsync(TRANSLATE_API_URL, request);

                if (response.IsSuccessStatusCode)
                {
                    string resultStr = await response.Content.ReadAsStringAsync();

                    DeepLTranslateResult translateResult = JsonConvert.DeserializeObject <DeepLTranslateResult>(resultStr);
                    if (translateResult.translations?.Length > 0)
                    {
                        return(translateResult.translations[0].text);
                    }
                    else
                    {
                        errorInfo = "Cannot get translation from: " + resultStr;
                        return(null);
                    }
                }
                else
                {
                    errorInfo = "API return code: " + response.StatusCode;
                    return(null);
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
        }
コード例 #4
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (desLang == "kr")
            {
                desLang = "ko";
            }
            if (srcLang == "kr")
            {
                srcLang = "ko";
            }
            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            var    hc     = CommonFunction.GetHttpClient();
            string apiurl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + ApiKey + "&lang=" + srcLang + "-" + desLang + "&text=";

            try
            {
                string retString = await hc.GetStringAsync(apiurl + HttpUtility.UrlEncode(sourceText));

                var doc = JsonConvert.DeserializeObject <Result>(retString);
                return(doc.text[0]);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
        }
コード例 #5
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (desLang == "kr")
            {
                desLang = "ko";
            }
            if (srcLang == "kr")
            {
                srcLang = "ko";
            }
            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            // 原文
            string q = sourceText;

            string retString;

            var sb = new StringBuilder("https://api.niutrans.com/NiuTransServer/translation?")
                     .Append("&from=").Append(srcLang)
                     .Append("&to=").Append(desLang)
                     .Append("&apikey=").Append(apiKey)
                     .Append("&src_text=").Append(Uri.EscapeDataString(q));

            string url = sb.ToString();

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = await hc.GetStringAsync(url);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            XiaoniuTransOutInfo oinfo = JsonConvert.DeserializeObject <XiaoniuTransOutInfo>(retString);

            if (oinfo.error_code == null || oinfo.error_code == "52000")
            {
                //得到翻译结果
                if (oinfo.tgt_text != null)
                {
                    return(oinfo.tgt_text);
                }
                else
                {
                    errorInfo = "UnknownError";
                    return(null);
                }
            }
            else
            {
                if (oinfo.error_msg != null)
                {
                    errorInfo = "ErrorID:" + oinfo.error_msg;
                    return(null);
                }
                else
                {
                    errorInfo = "UnknownError";
                    return(null);
                }
            }
        }
コード例 #6
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "zh")
            {
                desLang = "zh_cn";
            }
            if (srcLang == "zh")
            {
                srcLang = "zh_cn";
            }

            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            // 原文
            string q = HttpUtility.UrlEncode(sourceText);
            string retString;

            string trans_type = srcLang + "2" + desLang;

            trans_type = trans_type.ToUpper();
            string url = "https://fanyi.youdao.com/translate?&doctype=json&type=" + trans_type + "&i=" + q;

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = await hc.GetStringAsync(url);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            YoudaoTransResult oinfo;

            try
            {
                oinfo = JsonConvert.DeserializeObject <YoudaoTransResult>(retString);
            }
            catch (JsonException)
            {
                errorInfo = "Deserialize failed. Possibly due to quota limits.";
                return(null);
            }

            if (oinfo.errorCode == 0)
            {
                var sb = new StringBuilder(32);
                foreach (var youdaoTransDataList in oinfo.translateResult)
                {
                    foreach (var youdaoTransDataItem in youdaoTransDataList)
                    {
                        sb.Append(youdaoTransDataItem.tgt);
                    }
                }
                return(sb.ToString());
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.errorCode;
                return(null);
            }
        }
コード例 #7
0
        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (desLang == "kr")
            {
                desLang = "ko";
            }
            if (srcLang == "kr")
            {
                srcLang = "ko";
            }
            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }
            if (desLang != "en" && srcLang != "en")
            {
                sourceText = Translate(sourceText, "en", srcLang);
                if (sourceText == null)
                {
                    return(null);
                }
                srcLang = "en";
            }

            HttpResponseMessage resp;
            var hc  = CommonFunction.GetHttpClient();
            var req = new HttpRequestMessage(HttpMethod.Post, URL);

            req.Content = new StringContent("{\"text\":[\"" + sourceText.Replace("\"", "") + "\"],\"model_id\":\"" + srcLang + "-" + desLang + "\"}", null, "application/json");
            req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(ApiKey)));

            try
            {
                resp = hc.SendAsync(req).GetAwaiter().GetResult();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            finally
            {
                req.Dispose();
            }

            string retString     = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            var    dynamicResult = JsonConvert.DeserializeObject <dynamic>(retString);

            if (!resp.IsSuccessStatusCode)
            {
                errorInfo = dynamicResult.error;
                return(null);
            }

            string result = dynamicResult.translations[0].translation;

            return(result);
        }
コード例 #8
0
        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            // 原文
            string q = sourceText;
            string retString;

            string trans_type = srcLang + "2" + desLang;

            string url = "https://api.interpreter.caiyunai.com/v1/translator";
            //json参数
            string jsonParam = "{\"source\": [\"" + q + "\"], \"trans_type\": \"" + trans_type + "\", \"request_id\": \"demo\", \"detect\": true}";

            var hc  = CommonFunction.GetHttpClient();
            var req = new StringContent(jsonParam, null, "application/json");

            req.Headers.Add("X-Authorization", "token " + caiyunToken);
            try
            {
                retString = hc.PostAsync(url, req).GetAwaiter().GetResult().Content.ReadAsStringAsync().GetAwaiter().GetResult();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            finally
            {
                req.Dispose();
            }

            CaiyunTransResult oinfo;

            try
            {
                oinfo = JsonConvert.DeserializeObject <CaiyunTransResult>(retString);
            }
            catch {
                errorInfo = "JsonConvert Error";
                return(null);
            }

            if (oinfo.target?.Count >= 1)
            {
                //得到翻译结果
                return(string.Join("", oinfo.target.Select(x => Regex.Unescape(x))));
            }
            else
            {
                errorInfo = "ErrorInfo:" + oinfo.message;
                return(null);
            }
        }
コード例 #9
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "kr")
            {
                desLang = "kor";
            }
            if (srcLang == "kr")
            {
                srcLang = "kor";
            }
            if (desLang == "fr")
            {
                desLang = "fra";
            }
            if (srcLang == "fr")
            {
                srcLang = "fra";
            }

            // 原文
            string q = HttpUtility.UrlEncode(sourceText);
            string retString;

            var url = new StringBuilder()
                      .Append("https://v1.alapi.cn/api/fanyi?")
                      .Append("q=").Append(q)
                      .Append("&from=").Append(srcLang)
                      .Append("&to=").Append(desLang);

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = await hc.GetStringAsync(url.ToString());
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            AliapiTransResult oinfo = JsonConvert.DeserializeObject <AliapiTransResult>(retString);

            if (oinfo.msg == "success")
            {
                //得到翻译结果
                if (oinfo.data.trans_result.Count == 1)
                {
                    return(string.Join("", oinfo.data.trans_result.Select(x => x.dst)));
                }
                else
                {
                    errorInfo = "UnknownError";
                    return(null);
                }
            }
            else
            {
                errorInfo = "Error:" + oinfo.msg;
                return(null);
            }
        }
コード例 #10
0
        private string errorInfo; //错误信息

        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "kr")
            {
                desLang = "kor";
            }
            if (srcLang == "kr")
            {
                srcLang = "kor";
            }
            if (desLang == "fr")
            {
                desLang = "fra";
            }
            if (srcLang == "fr")
            {
                srcLang = "fra";
            }

            // 原文
            string q = sourceText;

            string retString;

            Random rd   = new Random();
            string salt = rd.Next(100000).ToString();

            string sign = CommonFunction.EncryptString(appId + q + salt + secretKey);
            var    sb   = new StringBuilder("https://api.fanyi.baidu.com/api/trans/vip/translate?")
                          .Append("q=").Append(HttpUtility.UrlEncode(q))
                          .Append("&from=").Append(srcLang)
                          .Append("&to=").Append(desLang)
                          .Append("&appid=").Append(appId)
                          .Append("&salt=").Append(salt)
                          .Append("&sign=").Append(sign);
            string url = sb.ToString();

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = hc.GetStringAsync(url).GetAwaiter().GetResult();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            BaiduTransOutInfo oinfo = JsonConvert.DeserializeObject <BaiduTransOutInfo>(retString);

            if (oinfo.error_code == null || oinfo.error_code == "52000")
            {
                //得到翻译结果
                if (oinfo.trans_result.Count == 1)
                {
                    return(oinfo.trans_result[0].dst);
                }
                else
                {
                    errorInfo = "UnknownError";
                    return(null);
                }
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.error_code;
                return(null);
            }
        }
コード例 #11
0
        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "kr")
            {
                desLang = "kor";
            }
            if (srcLang == "kr")
            {
                srcLang = "kor";
            }
            if (desLang == "fr")
            {
                desLang = "fra";
            }
            if (srcLang == "fr")
            {
                srcLang = "fra";
            }

            // 原文
            string q = sourceText;
            string retString;


            string url = "https://v1.alapi.cn/api/fanyi?q=" + q + "&from=" + srcLang + "&to=" + desLang;

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = hc.GetStringAsync(url).GetAwaiter().GetResult();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            AliapiTransResult oinfo = JsonConvert.DeserializeObject <AliapiTransResult>(retString);

            if (oinfo.msg == "success")
            {
                //得到翻译结果
                if (oinfo.data.trans_result.Count == 1)
                {
                    return(string.Join("", oinfo.data.trans_result.Select(x => x.dst)));
                }
                else
                {
                    errorInfo = "UnknownError";
                    return(null);
                }
            }
            else
            {
                errorInfo = "Error:" + oinfo.msg;
                return(null);
            }
        }
コード例 #12
0
        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (desLang == "zh")
            {
                desLang = "zh-cn";
            }
            if (srcLang == "zh")
            {
                srcLang = "zh-cn";
            }

            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            if (desLang == "kr")
            {
                desLang = "ko";
            }
            if (srcLang == "kr")
            {
                srcLang = "ko";
            }

            string fun = string.Format(@"TL('{0}')", sourceText);

            var tk = ExecuteScript(fun, GetTkkJS);

            string googleTransUrl = "https://translate.google.cn/translate_a/single?client=gtx&dt=t&sl=" + srcLang + "&tl=" + desLang + "&tk=" + tk + "&q=" + HttpUtility.UrlEncode(sourceText);

            var hc = CommonFunction.GetHttpClient();

            try
            {
                var ResultHtml = hc.GetStringAsync(googleTransUrl).GetAwaiter().GetResult();

                dynamic TempResult = Newtonsoft.Json.JsonConvert.DeserializeObject(ResultHtml);

                string ResultText = "";

                if (TempResult != null)
                {
                    for (int i = 0; i < TempResult[0].Count; i++)
                    {
                        if (TempResult[0][i] != null)
                        {
                            ResultText += TempResult[0][i][0];
                        }
                    }
                }

                return(ResultText);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
        }
コード例 #13
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (desLang == "kr")
            {
                desLang = "ko";
            }
            if (srcLang == "kr")
            {
                srcLang = "ko";
            }
            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }
            if (desLang != "en" && srcLang != "en")
            {
                sourceText = await TranslateAsync(sourceText, "en", srcLang);

                if (sourceText == null)
                {
                    return(null);
                }
                srcLang = "en";
            }

            HttpResponseMessage resp;
            var    hc        = CommonFunction.GetHttpClient();
            var    req       = new HttpRequestMessage(HttpMethod.Post, URL);
            string jsonParam = JsonConvert.SerializeObject(new Dictionary <string, object>
            {
                { "text", new string[] { sourceText } },
                { "model_id", srcLang + "-" + desLang }
            });

            req.Content = new StringContent(jsonParam, null, "application/json");
            req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(ApiKey)));

            try
            {
                resp = await hc.SendAsync(req);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            finally
            {
                req.Dispose();
            }

            string retString = await resp.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <Result>(retString);

            if (!resp.IsSuccessStatusCode)
            {
                errorInfo = result.error;
                return(null);
            }

            return(result.translations[0].translation);
        }
コード例 #14
0
        private string errorInfo; //错误信息

        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "kr")
            {
                desLang = "kor";
            }
            if (srcLang == "kr")
            {
                srcLang = "kor";
            }
            if (desLang == "fr")
            {
                desLang = "fra";
            }
            if (srcLang == "fr")
            {
                srcLang = "fra";
            }

            // 原文
            string q = sourceText;

            string retString;

            string salt = CommonFunction.RD.Next(100000).ToString();

            string sign = CommonFunction.EncryptString(appId + q + salt + secretKey);
            var    sb   = new StringBuilder("https://api.fanyi.baidu.com/api/trans/vip/translate?")
                          .Append("q=").Append(HttpUtility.UrlEncode(q))
                          .Append("&from=").Append(srcLang)
                          .Append("&to=").Append(desLang)
                          .Append("&appid=").Append(appId)
                          .Append("&salt=").Append(salt)
                          .Append("&sign=").Append(sign);
            string url = sb.ToString();

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = await hc.GetStringAsync(url);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            BaiduTransOutInfo oinfo = JsonConvert.DeserializeObject <BaiduTransOutInfo>(retString);

            if (oinfo.error_code == null || oinfo.error_code == "52000")
            {
                // 52000就是成功
                if (oinfo.trans_result.Length == 0)
                {
                    return("");
                }
                else if (oinfo.trans_result.Length == 1)
                {
                    return(oinfo.trans_result[0].dst);
                }
                else
                {
                    var sb2 = new StringBuilder();
                    foreach (var entry in oinfo.trans_result)
                    {
                        sb2.AppendLine(entry.dst);
                    }
                    return(sb2.ToString());
                }
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.error_code;
                return(null);
            }
        }
コード例 #15
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            // 原文
            string q = HttpUtility.UrlEncode(sourceText);

            string retString;

            string salt = CommonFunction.RD.Next(100000).ToString();

            string url = "https://tmt.tencentcloudapi.com/?";

            // 签名,参数使用未URL编码的值
            var sb = new StringBuilder()
                     .Append("Action=TextTranslate")
                     .Append("&Nonce=").Append(salt)
                     .Append("&ProjectId=0")
                     .Append("&Region=ap-shanghai")
                     .Append("&SecretId=").Append(SecretId)
                     .Append("&Source=").Append(srcLang)
                     .Append("&SourceText=").Append(sourceText)
                     .Append("&Target=").Append(desLang)
                     .Append("&Timestamp=").Append(CommonFunction.GetTimeStamp())
                     .Append("&Version=2018-03-21");
            string req = sb.ToString();

            HMACSHA1 hmac = new HMACSHA1()
            {
                Key = Encoding.UTF8.GetBytes(SecretKey)
            };

            byte[] data   = Encoding.UTF8.GetBytes("GETtmt.tencentcloudapi.com/?" + req);
            var    result = hmac.ComputeHash(data);

            hmac.Dispose();

            // 请求参数,参数使用URL编码后的值
            sb = new StringBuilder()
                 .Append("Action=TextTranslate")
                 .Append("&Nonce=").Append(salt)
                 .Append("&ProjectId=0")
                 .Append("&Region=ap-shanghai")
                 .Append("&SecretId=").Append(SecretId)
                 .Append("&Source=").Append(srcLang)
                 .Append("&SourceText=").Append(q)
                 .Append("&Target=").Append(desLang)
                 .Append("&Timestamp=").Append(CommonFunction.GetTimeStamp())
                 .Append("&Version=2018-03-21")
                 .Append("&Signature=").Append(HttpUtility.UrlEncode(Convert.ToBase64String(result)));
            req = sb.ToString();

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = await hc.GetStringAsync(url + req);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            TencentOldTransOutInfo oinfo = JsonConvert.DeserializeObject <TencentOldTransOutInfo>(retString);

            if (oinfo.Response.Error == null)
            {
                //得到翻译结果
                return(oinfo.Response.TargetText);
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.Response.Error.Value.Code + " ErrorInfo:" + oinfo.Response.Error.Value.Message;
                return(null);
            }
        }
コード例 #16
0
        public string Translate(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "zh")
            {
                desLang = "zh_cn";
            }
            if (srcLang == "zh")
            {
                srcLang = "zh_cn";
            }

            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            // 原文
            string q = sourceText;
            string retString;

            string trans_type = srcLang + "2" + desLang;

            trans_type = trans_type.ToUpper();
            string url = "https://fanyi.youdao.com/translate?&doctype=json&type=" + trans_type + "&i=" + q;

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = hc.GetStringAsync(url).GetAwaiter().GetResult();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            YoudaoTransResult oinfo = JsonConvert.DeserializeObject <YoudaoTransResult>(retString);

            if (oinfo.errorCode == 0)
            {
                //得到翻译结果
                if (oinfo.translateResult.Count == 1)
                {
                    return(string.Join("", oinfo.translateResult[0].Select(x => x.tgt)));
                }
                else
                {
                    errorInfo = "UnknownError";
                    return(null);
                }
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.errorCode;
                return(null);
            }
        }
コード例 #17
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            if (desLang == "jp")
            {
                desLang = "ja";
            }
            if (srcLang == "jp")
            {
                srcLang = "ja";
            }

            // 原文
            string q = sourceText;
            string retString;

            string trans_type = srcLang + "2" + desLang;

            string url = "https://api.interpreter.caiyunai.com/v1/translator";
            //json参数
            string jsonParam = JsonConvert.SerializeObject(new Dictionary <string, object>
            {
                { "source", new string[] { q } },
                { "trans_type", trans_type },
                { "request_id", "demo" },
                { "detect", true }
            });

            var hc  = CommonFunction.GetHttpClient();
            var req = new StringContent(jsonParam, null, "application/json");

            req.Headers.Add("X-Authorization", "token " + caiyunToken);
            try
            {
                retString = await(await hc.PostAsync(url, req)).Content.ReadAsStringAsync();
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (System.Threading.Tasks.TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            finally
            {
                req.Dispose();
            }

            CaiyunTransResult oinfo;

            try
            {
                oinfo = JsonConvert.DeserializeObject <CaiyunTransResult>(retString);
            }
            catch {
                errorInfo = "JsonConvert Error";
                return(null);
            }

            if (oinfo.target?.Length >= 1)
            {
                //得到翻译结果
                return(string.Join("", oinfo.target.Select(x => Regex.Unescape(x))));
            }
            else
            {
                errorInfo = "ErrorInfo:" + oinfo.message;
                return(null);
            }
        }