百度翻译api :http://developer.baidu.com/wiki/index.php?title=帮助文档首页/百度翻译/翻译AP
核心翻译类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Security.Cryptography;
namespace BaiduTrans
{
public class BaiduTrans
{
/// <summary>
/// 1. + URL 中+号表示空格 %2B
///2. 空格 URL中的空格可以用+号或者编码 %20
///3. / 分隔目录和子目录 %2F
///4. ? 分隔实际的 URL 和参数 %3F
///5. % 指定特殊字符 %25
///6. # 表示书签 %23
///7. & URL 中指定的参数间的分隔符 %26
///8. = URL 中指定参数的值 %3D
/// </summary>
public string TransContent(string content)
{
if(string.IsNullOrEmpty(content)) return"";
WebClient client = new WebClient();
content = content.Replace(@"#", "%23");
string appID = "2015063000000001";
string pkey = "12345678";
string sign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(appID + content + "1435660288" + pkey, "MD5");
string url = string.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}\&appid={1}\&salt=1435660288\&from=auto\&to=auto\&sign={2}", content, appID, sign.ToLower());
var buffer = client.DownloadData(url);
string result = Encoding.UTF8.GetString(buffer);
StringReader sr = new StringReader(result);
JsonTextReader jsonReader = new JsonTextReader(sr);
JsonSerializer serializer = new JsonSerializer();
var r = serializer.Deserialize<TransObj>(jsonReader);
return r.trans_result[0].dst;
}
}
}
对象类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BaiduTrans
{
public class TransObj
{
public string from { get; set; }
public string to { get; set; }
public List<TransResult> trans_result { get; set; }
}
public class TransResult
{
public string src { get; set; }
public string dst { get; set; }
}
}
调用实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BaiduTrans
{
class Program
{
static void Main(string[] args)
{
while (true)
{
System.Console.Out.WriteLine("输入要翻译的内容:");
string src = System.Console.ReadLine();
BaiduTrans bt = new BaiduTrans();
string ret = bt.TransContent(src);
System.Console.Out.WriteLine("翻译内容如下:");
System.Console.Out.WriteLine(ret);
}
}
}
}