个人资料

跳过导航链接首页 > 博客列表 > 博客正文

c#使用百度翻译接口(更新修复)

分类:

     定义baidu返回的json对应的类

namespace EasyNote.Translate.Baidu
{

	public class Rootobject
	{
		public string from { get; set; }
		public string to { get; set; }
		public string domain { get; set; }
		public int type { get; set; }
		public int status { get; set; }
		
		public int error { get; set; }
		public string msg { get; set; }

		public Trans_Result[] trans_result { get; set; }
	}

	public class Trans_Result
	{
		public string src { get; set; }
		public string dst { get; set; }

		public int prefixWrap { get; set; }

		public object[] relation { get; set; }
		public object[][] result { get; set; }
	}





}

调用方法:

		public static async Task<EasyNote.Translate.Baidu.Rootobject> Baidu_Translate(string from, string to, string content)
		{
			// 原文
			string q = content;
			// 源语言
			// 改成您的APP ID
			string appId = "这个需要前往百度翻译平台注册获取自己的ID";
			Random rd = new Random();
			string salt = rd.Next(100000).ToString();
			// 改成您的密钥
			string secretKey = "百度翻译平台获取";
			string sign = EncryptString(appId + q + salt + secretKey);
			string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
			url += "q=" + HttpUtility.UrlEncode(q);
			url += "&from=" + from;
			url += "&to=" + to;
			url += "&appid=" + appId;
			url += "&salt=" + salt;
			url += "&sign=" + sign;
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.Method = "GET";
			request.ContentType = "text/html;charset=UTF-8";
			request.UserAgent = null;
			request.Timeout = 6000;
			//HttpWebResponse response = (HttpWebResponse)request.GetResponse();


			using (WebResponse response = await request.GetResponseAsync())
			{
				using (Stream myResponseStream = response.GetResponseStream())
				{
					using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")))
					{
						string retString = myStreamReader.ReadToEnd();
						Debug.WriteLine(retString);
						var result = JsonConvert.DeserializeObject<EasyNote.Translate.Baidu.Rootobject>(retString);
						return result;
					}
				}
				

			}





			
		}

		// 计算MD5值
		public static string EncryptString(string str)
		{
			MD5 md5 = MD5.Create();
			// 将字符串转换成字节数组
			byte[] byteOld = Encoding.UTF8.GetBytes(str);
			// 调用加密方法
			byte[] byteNew = md5.ComputeHash(byteOld);
			// 将加密结果转换为字符串
			StringBuilder sb = new StringBuilder();
			foreach (byte b in byteNew)
			{
				// 将字节转换成16进制表示的字符串,
				sb.Append(b.ToString("x2"));
			}
			// 返回加密的字符串
			return sb.ToString();
		}


百度翻译平台:http://api.fanyi.baidu.com/api/trans/product/apidoc


使用:

var res = await Translater.Baidu_Translate(MySettings.Baidu_From, MySettings.Baidu_To,redit.Document.Selection.Text);

res.dst是翻译的结果


admin
最初发表2019/1/19 23:01:52 最近更新2019/9/24 22:23:23 1302
为此篇作品打分
10
   评论