WP8.1小梦词典开发2:百度翻译API使用

原文出自:http://www.bcmeng.com/api2/

小梦昨天和大家分享了WP8.1金山词霸API使用方法,今天继续分享windows phone 8.1中百度翻译API的使用方法.和昨天一样首先我们需要申请百度翻译API的Key:

百度翻译API的Key的申请:

进入 http://developer.baidu.com/ 需要一个百度账号,注册登陆后. 点击右上方的  管理服务台 ,选择开发者服务管理,进入口,选择创建工程就可以.创建工程完成后,你就可以拿到你的Key.和金山词霸一样,要处理返回结果,我们必须知道数据返回的格式和发起请求的格式.

百度翻译API的说明:

http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%E9%A1%B5/%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91/%E7%99%BE%E5%BA%A6%E8%AF%8D%E5%85%B8API%E4%BB%8B%E7%BB%8D  里面的说明很详细,小梦就不多嘴了.

向百度翻译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 = "网络访问失败!";
            }
        }

百度翻译API使用源码下载:

点我下载!

原文地址:https://www.cnblogs.com/xdoudou/p/3945163.html