1. 程式人生 > >Google 翻譯API Demo

Google 翻譯API Demo

     上篇裡提到的介面呼叫方法是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("http://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;
        }

參考資料: