调用百度翻译需要一个API Key。具体可以去这里http://developer.baidu.com/console#app/project 申请,申请完以后就可以看到下面的页面:
获取以后就可以调用翻译API了 。
我们需要定义2个类存放返回的结果:
public class TranslationResult { public string Error_code { get; set; } public string Error_msg { get; set; } public string From { get; set; } public string To { get; set; } public string Query { get; set; } public Translation[] Trans_result { get; set; } }
public class Translation { public string Src { get; set; } public string Dst { get; set; } }
第一个类代表着返回结果的状态等信息,同时它还包含了真正的翻译结果,是一个Translation数组。因为你需要翻译的字符串可能是多行的所以是一个数组,当然你也可以把他定义成集合。而第二个类代表着翻译的每一行的原文和译文。
另外百度翻译的直接返回结果是一个JSON类型的字符串,所以我们可以通过System.Web.Script.Serialization.JavaScriptSerializer类进行反序列化,变成我上面定义的 那2个类,这就是为什么我定义的属性中会存在Error_code这样奇怪的名字。
此外我还定义了一个枚举,用来存放语言语种:
public enum Language { Auto = 0, ZH = 1, JP = 2, EN = 3, KOR = 4, SPA = 5, FRA = 6, TH = 7, ARA = 8, RU = 9, PT = 10, YUE = 11, WYW = 12, DE = 13, NL = 14, IT = 15, EL = 16 }
最后我们只需要向百度翻译发送请求就可以了:
public static TranslationResult GetTranslationFromBaiduFanyi(string source, Language from = Language.Auto, Language to = Language.Auto) { string jsonResult = string.Empty; string apiKey = "yourApiKey"; string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id={0}&q={1}&from={2}&to={3}", apiKey, HttpUtility.UrlEncode(source, Encoding.UTF8), from.ToString().ToLower(), to.ToString().ToLower()); WebClient wc = new WebClient(); try { jsonResult = wc.DownloadString(url); } catch (Exception e) { jsonResult = string.Empty; } JavaScriptSerializer jss = new JavaScriptSerializer(); TranslationResult ret = jss.Deserialize<TranslationResult>(jsonResult); return ret; }