Asp.Net Core 实现谷歌翻译ApI 免费版

  由于谷歌翻译官方API是付费版本,本着免费和开源的精神。分享一下用 Net Core 实现谷歌翻译API的代码。

项目引用的Nuget 包:

ChakraCore.NET

Newtonsoft.Json

JavaScriptEngineSwitcher.ChakraCore.Native.win-x86(特别说明一下"win-x86",代表程序运行环境。)

翻译地址https://translate.google.cn(国内可以访问)

参数说明

text:待翻译文本

sl:需要翻译的语言(中文:zh-CN,英文:en)

tl: 翻译结果的语言(中文:zh-CN,英文:en)

Asp.Net Core 实现谷歌翻译ApI 免费版

 public class HttpHelper
{
/// <summary>
/// 请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="args">参数</param>
/// <returns></returns>
public static string GetRequest(string url, CookieContainer cookieContainer, Dictionary<string, dynamic> args)
{
try
{
if (args.Count > )
{
var argStr = string.Empty; foreach (var item in args)
{
if (item.Key == null || item.Value == null)
{
continue;
}
argStr = $"{argStr}{item.Key}={item.Value}&";
} url = $"{url}?{argStr.TrimEnd('&')}";
} HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "get";
request.Timeout = ;
request.CookieContainer = cookieContainer;
request.UserAgent = GetUserAgent();
request.Headers.Add("X-Requested-With:XMLHttpRequest");
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{ return reader.ReadToEnd();
}
}
}
catch (Exception)
{
return string.Empty;
}
} /// <summary>
/// 用户代理
/// </summary>
/// <returns></returns>
private static string GetUserAgent()
{
var userAgents = new List<string>
{
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
"Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 ",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.14) Gecko/20110218 AlexaToolbar/alxf-2.0 Firefox/3.6.14",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
"Opera/9.80 (Android 2.3.4; Linux; Opera mobi/adr-1107051709; U; zh-cn) Presto/2.8.149 Version/11.10",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
"Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
}; return userAgents.OrderBy(x => Guid.NewGuid()).First();
}
}

HttpHelper

 /// <summary>
/// 翻译 助手
/// </summary>
public static class TranslationHelper
{
/// <summary>
/// Chakra 上下文
/// </summary>
private static readonly ChakraContext _chakraContext; /// <summary>
/// Cookie
/// </summary>
private static readonly CookieContainer _cookieContainer; /// <summary>
/// 请求地址
/// </summary>
private static readonly string _baseUrl; /// <summary>
/// 静态
/// </summary>
static TranslationHelper()
{
var runtime = ChakraRuntime.Create(); _baseUrl = "http://translate.google.cn/translate_a/single";
_cookieContainer = new CookieContainer();
_chakraContext = runtime.CreateContext(true); var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var jsFileText = File.ReadAllText($@"{basePath}\gettk.js"); _chakraContext.RunScript(jsFileText); //运行脚本
} /// <summary>
/// 获取翻译结果(需要翻译的文字默认使用中文)
/// </summary>
/// <param name="toLang">语言</param>
/// <param name="originalText">待翻译的文本</param>
/// <returns></returns>
public static string GetTranslation(this string toLang, string originalText)
{
if (string.IsNullOrEmpty(toLang))
{
return toLang;
}
if (string.IsNullOrEmpty(originalText))
{
return originalText;
} return GetTranslation("zh-cn", toLang, originalText); } /// <summary>
/// 获取翻译结果
/// </summary>
/// <param name="fromLang">需要翻译的语言</param>
/// <param name="toLang">翻译结果的语言</param>
/// <param name="originalText">待翻译文本</param>
/// <returns></returns>
public static string GetTranslation(this string fromLang, string toLang, string originalText)
{
var args = new Dictionary<string, dynamic>
{
{ "client", "t" },
{ "sl", fromLang },
{ "tl", toLang },
{ "dt", "t" },
{ "tk", GetTK(originalText) },
{ "text", HttpUtility.UrlEncode(originalText) }
}; var result = HttpHelper.GetRequest(_baseUrl, _cookieContainer, args); return result.FormattedJson();
} /// <summary>
/// 获取TK
/// </summary>
/// <param name="originalText"></param>
/// <returns></returns>
private static string GetTK(string originalText)
{
_chakraContext.GlobalObject.WriteProperty("originalText", originalText);
return _chakraContext.RunScript("getTK(originalText)");
} /// <summary>
/// 格式化Json
/// </summary>
/// <param name="jsonStr">Json</param>
/// <returns></returns>
private static string FormattedJson(this string jsonStr)
{
if (string.IsNullOrEmpty(jsonStr))
{
return string.Empty;
} var array = JsonConvert.DeserializeObject<JArray>(jsonStr); var result = array[][][].ToString(); return result;
} }

TranslationHelper

参考:C#实现谷歌翻译API

上一篇:是否可以仅使用JDK或HttpComponents处理JSON响应?


下一篇:iOS学习之Object-C语言内存管理