利用谷歌翻譯API實現(xiàn)谷歌翻譯函數(shù):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string text = "Artificial intelligence is a branch of computer science. Artificial intelligence is a branch of computer science.";
string text1 = "Artificial [intelligence] is a branch of computer science.";
string text2 = "Artificial intelligence is a branch of computer science Tom said.";
Console.WriteLine(googleTranslation(text));
Console.WriteLine(googleTranslation(text1));
Console.WriteLine(googleTranslation(text2));
}
public static string googleTranslation(string text)
{
if (text == "" || text == null)
{
return "";
}
else
{
string result = "";
string url = "https://translate.google.cn/translate_a/single?client=gtx&sl=en&tl=zh-CN&dt=t&q=" + text;
string jsonData = GetInfo(url);
string pattern = "\"([^\"]*)\"";
int count = Regex.Matches(jsonData, pattern).Count;
MatchCollection matches = Regex.Matches(jsonData, pattern);
for (int i = 0; i < count - 1; i += 2)
{
result += matches[i].Value.Trim().Replace("\"", "");
}
return result;
}
}
public static bool InChinese(string StrChineseString)
{
return Regex.IsMatch(StrChineseString, ".*[\\u4e00-\\u9faf].*");
}
public static string GetInfo(string url)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//訪問http方法
string strBuff = "";
Uri httpURL = new Uri(url);
///HttpWebRequest類繼承于WebRequest咖祭,并沒有自己的構(gòu)造函數(shù)济欢,需通過WebRequest的Creat方法建立,并進行強制的類型轉(zhuǎn)換
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
///通過HttpWebRequest的GetResponse()方法建立HttpWebResponse,強制類型轉(zhuǎn)換
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
///GetResponseStream()方法獲取HTTP響應(yīng)的數(shù)據(jù)流,并嘗試取得URL中所指定的網(wǎng)頁內(nèi)容
///若成功取得網(wǎng)頁的內(nèi)容,則以System.IO.Stream形式返回诡右,若失敗則產(chǎn)生ProtoclViolationException錯誤琅翻。在此正確的做法應(yīng)將以下的代碼放到一個try塊中處理。這里簡單處理
Stream respStream = httpResp.GetResponseStream();
///返回的內(nèi)容是Stream形式的揣钦,所以可以利用StreamReader類獲取GetResponseStream的內(nèi)容获询,并以
//StreamReader類的Read方法依次讀取網(wǎng)頁源程序代碼每一行的內(nèi)容,直至行尾(讀取的編碼格式:UTF8)
StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
strBuff = respStreamReader.ReadToEnd();
return strBuff;
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
//直接確認拐袜,否則打不開
return true;
}
}
}