有次拉uistring.txt翻译时发现百度翻译有字符限制2000汉字,就想可以客户端自己调用百度翻译API进行几万行数据的处理,进行尝试:
参考网址:
1.官网API接入方式: http://api.fanyi.baidu.com/api/trans/product/apidoc
2.C#数据解析流程:http://blog.csdn.net/wszll_alex/article/details/46381565
3.MD5解析:https://www.cnblogs.com/dgjack/archive/2010/12/30/1921492.html
实现:翻译单词 apple为汉语
主要代码:
string myInputString = ""; string mAppID = ""; string mySecurityID = ""; int mySalt = 0; //mAppIDmyInputStringmySaltmySecurityID StringBuilder mySignString = new StringBuilder(); string myMd5Result = string.Empty; //1.拼接字符,为了生成sign mySignString.Append(mAppID); mySignString.Append(myInputString); mySignString.Append(mySalt); mySignString.Append(mySecurityID); //2.通过md5获取sign byte[] sourceMd5Byte = Encoding.Default.GetBytes(mySignString.ToString()); MD5 md5 = new MD5CryptoServiceProvider(); byte[] destMd5Byte = md5.ComputeHash(sourceMd5Byte); myMd5Result = BitConverter.ToString(destMd5Byte).Replace("-", ""); myMd5Result = myMd5Result.ToLower(); //3.获取web翻译的json结果 WebClient client = new WebClient(); string url = string.Format ("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from=en&to=zh&appid={1}&salt={2}&sign={3}", myInputString, mAppID, mySalt, myMd5Result); byte[] 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); txtResult.Text = r.trans_result[0].dst;
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; } }
总结:1.MD5的生成, 把密码id放入md5中,然后百度那边也有我的密码id,百度进行校验。
2.NuGet进行Json的数据处理 根据官网文档返回的字符串类型定义好数据类
3.WebClient类的使用