首先先在百度翻译开放平台上注册一下,然后得到两个关键值:App Id 和 秘钥,有了这俩就可以直接写程序了。
写程序的时候参考一下开发手册
因为最后的返回结果是这样的
{"from":"en","to":"zh","trans_result":[{"src":"hello","dst":"\u4f60\u597d"}]}
先定义一个Translation.cs用了存放结果中的trans_result
public class Translation
{
public string Src { get; set; }
public string Dst { get; set; }
}
再定义一个TranslationResult存放上面结果的反序列化的结果
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; }
}
之后是主体功能:拼接URL并访问然后得到结果
我现在使用的版本URL拼接格式是:
http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
也就是 百度翻译网址+要翻译的字符串+源语言+目的语言+appid+随机数字+md5校验值
这个有可能会变,反正这些帮助文档上写的都很详细
public static TranslationResult GetTranslationFromBaiduFanyi(String source, Language from = Language.Auto, Language to = Language.Auto)
{
String jsonResult = String.Empty;
String languageFrom = from.ToString().ToLower();
String languageTo = to.ToString().ToLower();
String appId = "123321123321";
String randomNum = System.DateTime.Now.Millisecond.ToString();
String md5Sign = GetMD5HashFromFile(appId + source + randomNum + "09090909090909");
Console.WriteLine(appId + source + randomNum + "Cxdi54XVRAnuMAbOjCMr");
String url = String.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}",
HttpUtility.UrlEncode(source, Encoding.UTF8),
languageFrom,
languageTo,
appId,
randomNum,
md5Sign
);
Console.WriteLine(url);
WebClient wc = new WebClient();
try
{
jsonResult = wc.DownloadString(url);
}
catch (Exception e)
{
jsonResult = string.Empty;
Console.WriteLine(e.Message);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
TranslationResult ret = jss.Deserialize<TranslationResult>(jsonResult);
return ret;
}
上面用到的MD5在我之前的博客或者网上都能找到
还用到了一个枚举定义语言类型
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
}
调用时
private static void Main(String[] args)
{
TranslationResult result = TranslateUtil.GetTranslationFromBaiduFanyi("hello", TranslateUtil.Language.EN, TranslateUtil.Language.ZH);
for (int i = 0; i < result.Trans_result.Length; i++)
{
Console.WriteLine(result.Trans_result[i].Dst);
}
}