WP8.1小梦词典开发1:金山词霸API使用

原文出自:http://www.bcmeng.com/windows-phone-api/

今天开始小梦给大家分享一下小梦词典开发中几个关键问题,首先我们来看查词功能的实现.小梦词典的查词功能是通过金山词霸的查词API来实现的.首先我们需要申请金山词霸API的key:

金山词霸API的key申请:

申请地址:http://open.iciba.com/?c=api#jhjy   进入后输入您的网站名,网站地址和你的邮箱就可以,key会发送到你的邮箱里.我试过了,网站名和网站地址可以随意填写,只要邮箱是你的就可以.

金山词霸查词API数据返回格式:

<?xml version="1.0" encoding="UTF-8"?>

-<dict name="219" id="219" num="219">

<key>love</key>

<ps>l?v</ps>

<pron>http://res.iciba.com/resource/amp3/oxford/0/4f/5b/4f5bbc0f19c33e5f1a0b6b974b4eacce.mp3</pron>

<ps>l?v</ps>

<pron>http://res.iciba.com/resource/amp3/1/0/b5/c0/b5c0b187fe309af0f4d35982fd961d7e.mp3</pron>

<pos>vt.& vi.</pos>

<acceptation>爱,热爱;爱戴;喜欢;赞美,称赞; </acceptation>

<pos>vt.</pos>

<acceptation>喜爱;喜好;喜欢;爱慕; </acceptation>

<pos>n.</pos>

<acceptation>爱情,爱意;疼爱;热爱;爱人,所爱之物; </acceptation>

-<sent>

<orig> They happily reflect the desire for a fusional love that inspired the legendary LOVE bracelet Cartier. </orig>

<trans> 快乐地反映出为富有传奇色彩的卡地亚LOVE手镯所赋予的水乳交融之爱恋情愫. </trans>

</sent>

-<sent>

<orig> Love is the radical of lovely , loveliness , and loving. </orig>

<trans> Love是lovely, loveliness 及loving的词根. </trans>

</sent>

-<sent>

<orig> She rhymes " love " with " dove ". </orig>

<trans> 她将 " love "" dove " 两字押韵. </trans>

</sent>

-<sent>

<orig> In sports, love means nil. </orig>

<trans> 体育中, love的意思是零. </trans>

</sent>

-<sent>

<orig> Ludde Omholt with his son, Love, in S ? derma a bohemian and culturally rich district in Stockholm. </orig>

<trans> LuddeOmholt和他的儿子Love在南城 —— 斯德哥尔摩市 的一个充满波西米亚风情的文化富饶区散步. </trans>

</sent>

</dict>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.Connectivity;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace jinshanAPI
{

    public sealed partial class MainPage : Page
    {
         string keyWord = null;
        HttpClient httpClient = null;
        public static string loadKey = "1F9CA812CB18FFDFC95FC17E9C57A5E1";
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;
            httpClient = new HttpClient();
            httpClient.MaxResponseContentBufferSize = 256000;//缓冲的最大字节数
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");//发送的标题
        }

        private void txtKeywords_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                Search();
            }
        }

        async void Search()
        {
            bool isOnline = CheckNetwork();
            if (isOnline)
            {
                string temp = txtKeywords.Text.Trim();
                if (temp != keyWord && !string.IsNullOrEmpty(temp))
                {
                    keyWord = temp;
                    await SearchWordFromAPI(keyWord);
                }
            }

        }

        private async Task<bool> SearchWordFromAPI(string keyWord)
        {
            bool haveResult = false;
            string url = "http://dict-co.iciba.com/api/dictionary.php?w=" + keyWord + "&key=" + loadKey;
            XDocument xResult = null;
            try
            {
                HttpResponseMessage response = await httpClient.GetAsync(url);
                Stream responseBodyAsStream = await response.Content.ReadAsStreamAsync();
                xResult = XDocument.Load(responseBodyAsStream);
                XElement dict = null;
                if (xResult != null)
                {
                    dict = xResult.Root;
                }
                if (dict.Elements().Count() <= 1)
                {
                    txtMag.Visibility = Visibility.Visible;
                    spResult.Visibility = Visibility.Collapsed;
                    txtMag.Text = "亲:对不起!没有找到" + keyWord + "的相关词典解释";
                }
                else
                {
                    haveResult = true;
                    txtMag.Visibility = Visibility.Collapsed;
                    spResult.Visibility = Visibility.Visible;

                    IEnumerable<XElement> pss = dict.Elements(XName.Get("ps"));
                    if (pss.Count() == 2)
                    {
                        spPron.Visibility = Visibility.Visible;
                        List<XElement> psList = pss.ToList();
                        txtPsUK.Text = "英:" + "[" + psList[0].Value + "]";
                        txtPsUs.Text = "美:" + "[" + psList[1].Value + "]";
                    }
                    else if (pss.Count() == 1)
                    {
                        spPron.Visibility = Visibility.Visible;
                        XElement ps = pss.FirstOrDefault();
                        txtPsUK.Text = "[" + ps.Value + "]";
                        txtPsUs.Text = string.Empty;
                    }
                    else
                    {
                        txtPsUK.Text = string.Empty;
                        txtPsUs.Text = string.Empty;
                        spPron.Visibility = Visibility.Collapsed;
                    }

                    IEnumerable<XElement> prons = dict.Elements(XName.Get("pron"));
                    if (prons.Count() == 2)
                    {
                        List<XElement> pronlist = prons.ToList();
                        mePronUK.Source = new Uri(pronlist[0].Value);
                        mePronUs.Source = new Uri(pronlist[1].Value);
                        btnPronUK.Visibility = Visibility.Visible;
                        btnPronUs.Visibility = Visibility.Visible;
                    }
                    else if (prons.Count() == 1)
                    {
                        XElement pron = prons.FirstOrDefault();
                        mePronUK.Source = new Uri(pron.Value);
                        btnPronUK.Visibility = Visibility.Visible;
                        btnPronUs.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        btnPronUK.Visibility = Visibility.Collapsed;
                        btnPronUs.Visibility = Visibility.Collapsed;
                    }
                    IEnumerable<XElement> poss = dict.Elements(XName.Get("pos"));
                    List<string> posList = new List<string>();
                    if (poss.Count() > 0)
                    {
                        foreach (XElement pos in poss)
                        {
                            posList.Add(pos.Value);
                        }
                    }

                    IEnumerable<XElement> acceptations = dict.Elements(XName.Get("acceptation"));
                    spAcceptions.Children.Clear();
                    if (acceptations.Count() > 0)
                    {
                        int i = 0;
                        foreach (XElement acceptation in acceptations)
                        {
                            TextBlock textAcceptation = new TextBlock();
                            textAcceptation.FontSize = 20;
                            textAcceptation.TextWrapping = TextWrapping.Wrap;
                            textAcceptation.Margin = new Thickness(0);
                            textAcceptation.Text = posList[i] + acceptation.Value;
                            i++;
                            spAcceptions.Children.Add(textAcceptation);
                        }
                    }

                    IEnumerable<XElement> sents = dict.Elements(XName.Get("sent"));
                    spSends.Children.Clear();
                    if (sents.Count() > 0)
                    {
                        foreach (XElement sent in sents)
                        {
                            XElement orig = sent.Element(XName.Get("orig"));
                            TextBlock textOrig = new TextBlock();
                            textOrig.FontSize = 20;
                            textOrig.TextWrapping = TextWrapping.Wrap;
                            textOrig.Text = orig.Value;
                            spSends.Children.Add(textOrig);
                            XElement trans = sent.Element(XName.Get("trans"));
                            TextBlock textTrans = new TextBlock();
                            textTrans.FontSize = 20;
                            textTrans.TextWrapping = TextWrapping.Wrap;
                            textTrans.Text = trans.Value;
                            spSends.Children.Add(textTrans);
                        }
                    }

                }
            }
            catch
            {
                txtMag.Visibility = Visibility.Visible;
                spResult.Visibility = Visibility.Collapsed;
                txtMag.Text = "亲:网络访问失败!";
            }

            return haveResult;
        }

        bool CheckNetwork()
        {
            bool isOnline = false;
            ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
            if (InternetConnectionProfile == null)
            {
                txtMag.Visibility = Visibility.Visible;
                spResult.Visibility = Visibility.Collapsed;
                txtMag.Text = "亲:断网情况下无法显示词典内容!";

            }
            else
            {
                isOnline = true;
            }
            return isOnline;
        }

        private void btnPronUK_Click(object sender, RoutedEventArgs e)
        {
            mePronUK.Play();
        }

        private void txtPronUs_Click(object sender, RoutedEventArgs e)
        {
            mePronUs.Play();
        }
    }
}

源代码下载:

点我下载!

WP8.1小梦词典开发1:金山词霸API使用

上一篇:Windows Phone 8.1开发:触控和指针事件2


下一篇:windows phone 8.1开发:磁铁|Tile更新