原文出自:http://www.bcmeng.com/api2/
小梦昨天和大家分享了WP8.1金山词霸API使用方法,今天继续分享windows phone 8.1中百度翻译API的使用方法.和昨天一样首先我们需要申请百度翻译API的Key:
百度翻译API的Key的申请:
进入 http://developer.baidu.com/ 需要一个百度账号,注册登陆后. 点击右上方的 管理服务台 ,选择开发者服务管理,进入口,选择创建工程就可以.创建工程完成后,你就可以拿到你的Key.和金山词霸一样,要处理返回结果,我们必须知道数据返回的格式和发起请求的格式.
百度翻译API的说明:
向百度翻译API发出请求并处理数据:
void TranslateFromApi()
{
string client_id ="5viaBptRhtEjv0HmrB0zN0OV";
string src = txtSrc.Text.Trim();
txtDst.Text = "正在翻译";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://openapi.baidu.com/public/2.0/bmt/translate?client_id=" + client_id + "&q=" + src + "&from=" + from + "&to=" + to);
request.Method = "GET";
request.Headers["Cookie"] = "name=value";
request.BeginGetResponse(ResponseCallback, request);
} private async void ResponseCallback(IAsyncResult result)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
WebResponse webResponse = httpWebRequest.EndGetResponse(result);
using (Stream stream = webResponse.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
JsonObject joResponse = JsonObject.Parse(content);
if (joResponse.ContainsKey("error_msg"))
{
txtDst.Text = joResponse["error_msg"].GetString();
}
else
{
if (joResponse.ContainsKey("trans_result"))
{
string resultend = null;
foreach (JsonValue item in joResponse["trans_result"].GetArray())
{
resultend += item.GetObject().GetNamedString("dst") + Environment.NewLine;
}
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,() =>
{
txtDst.Text = resultend;
}); }
}
}
}
catch
{
txtDst.Text = "网络访问失败!";
}
}