c#调用百度翻译API问题:帮看看代码错在哪里

.Net技术 码拜 8年前 (2016-02-23) 2573次浏览
static public string Translate(string text, string langPair)
{
string from = langPair.Split(new char[] { “|” })[0];      // 源语言
string to = langPair.Split(new char[] { “|” })[1];        // 目标语言
string appid = “xxx”;        // 从百度申请的 appid
string key = “xxx”;      // 申请的 密钥
//string salt = new Random().Next(10000, 90000).ToString();   // 使用“随机数”(百度API要求):失败
string salt = “1435660288”;     // 使用“固定数字”:成功
//text = HttpUtility.UrlEncode(text, Encoding.UTF8);        // 不需要编码,已测试成功
string signSrc = appid + text + salt + key;     // 按照 appid+q+salt+密钥 的顺序拼接(百度API要求)
byte[] bytes = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(signSrc));     // 通过 MD5(32位)生成 sign(百度API要求)
//
// 格式化为“十六进制”字符串(百度API要求)
//
string sign = “”;
for (int i = 0; i < bytes.Length; i++)
{
sign = sign + bytes[i].ToString(“x”);     // 假如使用大写“X”,则格式后的字符是大写字母。
}
//
// 使用 WebClient 不需要对 URL 编码
//
string url = string.Format(
“http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}”,
text, from, to, appid, salt, sign);
//
// 翻译返回结果:
// {“from”:”en”,”to”:”zh”,”trans_result”:[{“src”:”hello”,”dst”:”xxxx”}]}
//
// 出错时:
// {“error_code”:”54001″,”error_msg”:”Invalid Sign”}
//
string json = new WebClient().DownloadString(url);
//throw new Exception(url);
//throw new Exception(json);
TransClass transClass = JsonConvert.DeserializeObject<TransClass>(json);
if (transClass.trans_result != null)
{
string result = transClass.trans_result[0].dst;
return result;
}
else
{
throw new Exception(json);      // 出错
}
}
调用时,会出错时: {“error_code”:”54001″,”error_msg”:”Invalid Sign”} ,问题出在哪里呢?
解决方案

80

Invalid Sign,虽然本人没去找百度api,但就这名字也知道签名错误……
另外确认Encoding.ASCII正确?常规不应该是Encoding.Utf8吗?否则非英文的怎么搞

10

Invalid Sign可能是签名不对,你再阅读一下文档和他给的例子,用它例子算下签名检测下对不对

10

调用函数的签名不对,仔细检查一下拼写和编码格式什么的都对不对。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c#调用百度翻译API问题:帮看看代码错在哪里
喜欢 (0)
[1034331897@qq.com]
分享 (0)