百度翻译API,C# demo
protected void Page_Load(object sender, EventArgs e) { var query = "高度600米"; var text = new TransCore().GetTransResult(query, "auto", "en"); Response.Write(text); }
public class TransCore { private TransApi api; public TransCore() { api = new TransApi("xxxxxxxxxx", "mAepVM9I5lSew6X5qKXY"); } public string GetTransResult(string query, string from, string to) { return api.getTransResult(query, from, to); } }
public class TransApi { private static string TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate"; private string appid; private string securityKey; public TransApi(string appid, string securityKey) { this.appid = appid; this.securityKey = securityKey; } public string getTransResult(string query, string from, string to) { Dictionary<string, string> Params = buildParams(query, from, to); return Utils.HttpGet(getUrlWithQueryString(TRANS_API_HOST, Params)); } public static string getUrlWithQueryString(string url, Dictionary<string, string> Params) { if (Params == null) { return url; } StringBuilder builder = new StringBuilder(url); if (url.Contains("?")) { builder.Append("&"); } else { builder.Append("?"); } int i = 0; foreach(var key in Params.Keys) { string value = Params[key]; if (value == null) { // 过滤空的key continue; } if (i != 0) { builder.Append('&'); } builder.Append(key); builder.Append('='); builder.Append(HttpUtility.UrlEncode(value)); i++; } return builder.ToString(); } private Dictionary<string, string> buildParams(string query, string from, string to) { Dictionary<string, string> Params = new Dictionary<string, string>(); Params.Add("q", query); Params.Add("from", from); Params.Add("to", to); Params.Add("appid", appid); // 随机数 string salt = DateTime.Now.Ticks.ToString(); Params.Add("salt", salt); // 签名 string src = appid + query + salt + securityKey; // 加密前的原文 Params.Add("sign", Utils.MD5(src)); return Params; } }
public static string MD5(string pwd) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.UTF8.GetBytes(pwd); byte[] md5data = md5.ComputeHash(data); md5.Clear(); string str = ""; for (int i = 0; i < md5data.Length; i++) { str += md5data[i].ToString("x").PadLeft(2, '0'); } return str; }
/// <summary> /// HTTP GET方式请求数据. /// </summary> /// <param name="url">URL.</param> /// <returns></returns> public static string HttpGet(string url) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; //request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "*/*"; request.Timeout = 15000; request.AllowAutoRedirect = false; WebResponse response = null; string responseStr = null; try { response = request.GetResponse(); if (response != null) { StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); responseStr = reader.ReadToEnd(); reader.Close(); } } catch (Exception) { throw; } finally { request = null; response = null; } return responseStr; }