谷歌翻译函数实现

 1using System; 2using System.Collections.Generic; 3using System.IO; 4using System.Linq; 5using System.Net; 6using System.Text; 7using System.Threading.Tasks; 8using System.Security.Cryptography.X509Certificates; 9using System.Net.Security;10using System.Text.RegularExpressions;1112namespace ConsoleApplication113{14    class Program15    {16        static void Main(string[] args)
17 {18 string text = "Artificial intelligence is a branch of computer science. Artificial intelligence is a branch of computer science.";19 string text1 = "Artificial [intelligence] is a branch of computer science.";20 string text2 = "Artificial intelligence is a branch of computer science Tom said.";21 Console.WriteLine(googleTranslation(text));22 Console.WriteLine(googleTranslation(text1));23 Console.WriteLine(googleTranslation(text2));24 }2526 public static string googleTranslation(string text)
27 {28 if (text == "" || text == null)29 {30 return "";31 }32 else33 {34 string result = "";35 string url = "https://translate.google.cn/translate_a/single?client=gtx&sl=en&tl=zh-CN&dt=t&q=" + text;36 string jsonData = GetInfo(url);37 string pattern = "\"([^\"]*)\"";38 int count = Regex.Matches(jsonData, pattern).Count;39 MatchCollection matches = Regex.Matches(jsonData, pattern);40 for (int i = 0; i < count - 1; i += 2)41 {42 result += matches[i].Value.Trim().Replace("\"", "");43 }44 return result;45 }46 }4748 public static string GetInfo(string url)
49 {50 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);51 //访问http方法 52 string strBuff = "";53 Uri httpURL = new Uri(url);54 ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法建立,并进行强制的类型转换 55 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);56 ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换 57 HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();58 ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容 59 ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理 60 Stream respStream = httpResp.GetResponseStream();61 ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以 62 //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8) 63 StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);64 strBuff = respStreamReader.ReadToEnd();65 return strBuff;66 }67 public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
68 {69 //直接确认,否则打不开 70 return true;71 }72 }73}