有次拉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類的使用
