975
技術社區[雲棲]
Google 翻譯API Demo
接上篇 Google翻譯API(B/S調用和C/S調用)
上篇裏提到的接口調用方法是get方式,這樣有個問題,每次請求翻譯的內容不能超過url允許的長度。需要改成post方式才行,但是google沒有提供post方式的API請求,怎麼辦呢?在通過網上一番資料的查找,在一位哥們的博客裏看到了解決方案,不過他用的是java版的,對應post地址和參數,寫出了.net版的。加上朗讀的功能,程序界麵如下:

/// <summary>
/// Post方式獲取翻譯
/// </summary>
/// <param name="sourceText"></param>
/// <param name="langPair"></param>
/// <returns></returns>
private static string TranslatePostMethod(string sourceText, string langPair)
{
string fromLan = langPair; //原始語言
string toLan = langPair.ToLower() == "zh" ? "en" : "zh"; //目標語言 這裏隻針對中英互轉
HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create("https://translate.google.com/translate_t#");
StringBuilder postContent = new StringBuilder();
Encoding myEncoding = Encoding.UTF8;
postContent.Append(HttpUtility.UrlEncode("hl", myEncoding));
postContent.Append("=");
postContent.Append(HttpUtility.UrlEncode("en", myEncoding));
postContent.Append("&");
postContent.Append(HttpUtility.UrlEncode("ie", myEncoding));
postContent.Append("=");
postContent.Append(HttpUtility.UrlEncode("UTF-8", myEncoding));
postContent.Append("&");
postContent.Append(HttpUtility.UrlEncode("sl", myEncoding));
postContent.Append("=");
postContent.Append(HttpUtility.UrlEncode(fromLan, myEncoding));
postContent.Append("&");
postContent.Append(HttpUtility.UrlEncode("text", myEncoding));
postContent.Append("=");
postContent.Append(HttpUtility.UrlEncode(sourceText, myEncoding));
postContent.Append("&");
postContent.Append(HttpUtility.UrlEncode("tl", myEncoding));
postContent.Append("=");
postContent.Append(HttpUtility.UrlEncode(toLan, myEncoding));
byte[] data = Encoding.ASCII.GetBytes(postContent.ToString());
requestScore.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
requestScore.Method = "Post";
//requestScore.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
requestScore.ContentLength = data.Length;
requestScore.KeepAlive = true;
requestScore.Timeout = (6 * 60 * 1000);
requestScore.ProtocolVersion = HttpVersion.Version10;
Stream stream = requestScore.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
string content = string.Empty;
try
{
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse();
StreamReader reader = new StreamReader(responseSorce.GetResponseStream());
content = reader.ReadToEnd();
responseSorce.Close();
reader.Dispose();
stream.Dispose();
}
catch (WebException ex)
{
HttpWebResponse responseSorce = (HttpWebResponse)ex.Response;//得到請求網站的詳細錯誤提示
StreamReader reader = new StreamReader(responseSorce.GetResponseStream());
content = reader.ReadToEnd();
responseSorce.Close();
reader.Dispose();
stream.Dispose();
}
finally
{
requestScore.Abort();
}
string reg = @"<(?<HtmlTag>[\w]+)[^>]*\s[iI][dD]=(?<Quote>[""']?)result_box(?(Quote)\k<Quote>)[""']?[^>]*>((?<Nested><\k<HtmlTag>[^>]*>)|</\k<HtmlTag>>(?<-Nested>)|.*?)*</\k<HtmlTag>>"; //返回的是一個html頁麵,需匹配出翻譯內容
Regex r = new Regex(reg);
MatchCollection mcItem = r.Matches(content);
string result = ConvertHtmlToText(mcItem[0].Value);
return "post:" + result;
}
可執行程序下載:https://download.csdn.net/source/3499399
源代碼下載:https://download.csdn.net/source/3499392
參考資料:
最後更新:2017-04-02 06:51:50