浏览器调用:
<html> <head> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> <!-- google.load("language", "1"); function initialize() { var text = document.getElementById("text").innerHTML; google.language.detect(text, function(result) { if (!result.error && result.language) { google.language.translate(text, result.language, "en", function(result) { var translated = document.getElementById("translation"); if (result.translation) { translated.innerHTML = result.translation; } }); } }); } google.setOnLoadCallback(initialize); //--> </script> </head> <body> <div id="text">你好,很高興見到你。</div> <div id="translation"></div> </body> </html>
客户端 调用:
将 Google翻译API封装成一个类:GoogleTranslateLib.cs
namespace GoogleTranslateLib { using System; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Text; using System.Web; [DataContract(Namespace = "http://ajax.googleapis.com/ajax/services/language/translate")] class Config { [DataMember(Order = 0)] public ResponseData responseData { get; set; } [DataMember(Order = 1)] public string responseDetails { get; set; } [DataMember(Order = 2)] public string responseStatus { get; set; } } [DataContract(Namespace = "http://ajax.googleapis.com/ajax/services/language/translate")] class ResponseData { [DataMember(Order = 0)] public string translatedText { get; set; } } class Translate { public static string translatezh2en(string sourceText, string langPair) { string result; string url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair="; url += HttpUtility.UrlEncode(langPair) + "&q=" + HttpUtility.UrlEncode(sourceText); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Referer = "http://www.my-ajax-site.com"; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); result = reader.ReadToEnd(); } catch (Exception) { return ""; } return result; } } }调用方法:
using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
namespace GoogleTranslateDemo
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("请输入您想翻译的字词:");
string inputStr = Console.ReadLine();
Console.WriteLine("翻译中,请稍后...");
string result = GoogleTranslateLib.Translate.translatezh2en(inputStr, "zh|en");
if (!string.IsNullOrEmpty(result))
{
var serializer = new DataContractJsonSerializer(typeof(GoogleTranslateLib.Config));
var mStream = new MemoryStream(Encoding.UTF8.GetBytes(result));
GoogleTranslateLib.Config readConfig = (GoogleTranslateLib.Config)serializer.ReadObject(mStream);
if (readConfig.responseStatus == "200")
{
string message = "原始内容:" + inputStr + Environment.NewLine + "翻译内容:" + readConfig.responseData.translatedText;
Console.WriteLine(message);
}
}
Console.ReadKey(true);
}
}
}
效果图: