65.9K
CodeProject 正在变化。 阅读更多。
Home

在 Windows Phone 7 上搜索 Twitter

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.69/5 (5投票s)

2011年2月24日

Ms-PL

2分钟阅读

viewsIcon

13330

在 Windows Phone 7 上搜索 Twitter

上一篇帖子中,我们已经了解了如何获取 Twitter 上的热门话题。
在这篇帖子中,我们将继续探索 Twitter 服务。我们将看到如何在 Twitter 上搜索推文。

image

搜索 Twitter

Twitter 公开了基于 JSON 的搜索服务,地址如下:

其中 {0} 应替换为您的搜索词。

结果以 JSON 数据格式返回,因此我们将再次使用 DataContractJsonSerializer。有关如何使用它的更多详细信息,请查看上一篇帖子。

定义推文和 TwitterResults

与我们在上一篇帖子中做的一样,我们需要声明一些 C# 模型类,用于解析 Twitter JSON 结果。

/// <summary>
/// Model for twit
/// </summary>
public class Twit
{
    /// <summary>
    /// Gets or sets the text.
    /// </summary>
    /// <value>The text.</value>
    public string text { get; set; }

    /// <summary>
    /// Gets the decoded text.
    /// </summary>
    /// <value>The decoded text.</value>
    public string DecodedText 
    {
        get
        {
            return HttpUtility.HtmlDecode(text);
        }
    }

    /// <summary>
    /// Gets or sets the from_user.
    /// </summary>
    /// <value>The from_user.</value>
    public string from_user { get; set; }

    /// <summary>
    /// Gets or sets the profile_image_url.
    /// </summary>
    /// <value>The profile_image_url.</value>
    public string profile_image_url { get; set; }

    /// <summary>
    /// Gets or sets the created_at.
    /// </summary>
    /// <value>The created_at.</value>
    public DateTime created_at { get; set; }
}

/// <summary>
/// Model for twitter results
/// </summary>
public class TwitterResults
{
    /// <summary>
    /// Gets or sets the results.
    /// </summary>
    /// <value>The results.</value>
    public Twit[] results { get; set; }
}

请注意,推文文本在使用前应进行 HTML 解码,因此我添加了一个 DecodedText 属性来完成这项工作。

实现 Twitter 搜索服务

我们将实现一个名为 TwitterService.Search static 方法,该方法将接收搜索词作为其第一个参数,以及几个委托,以允许我们的类异步工作

  • Action<IEnumerable<Twit>> onSearchCompleted,当 Twitter 搜索完成时将调用它。
  • Action<Exception> onError,如果在搜索 Twitter 时发生错误,将调用它。
  • Action onFinally,无论是否发生异常,都将始终调用它。将其视为一个常见的 try-catch 块中的 finally 部分。

因此,该方法签名将是

public static void Search(string searchText, Action<IEnumerable<Twit>> 
onSearchCompleted = null, Action<Exception> onError = null, Action onFinally = null)

要搜索 Twitter,我们将再次使用 WebClient

WebClient webClient = new WebClient();

// register on download complete event
webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
    ...
};

string encodedSearchText = HttpUtility.UrlEncode(searchText);
webClient.OpenReadAsync(new Uri
(string.Format(TwitterSearchQuery, encodedSearchText)));

其中 TwitterSearchQuery 定义如下

private const string TwitterSearchQuery = 
"http://search.twitter.com/search.json?q={0}";

其余代码处理不同的委托:SearchCompletedonErroronFinally。我在此完整地呈现该方法

/// <summary>
/// Searches the specified search text.
/// </summary>
/// <param name="searchText">The search text.</param>
/// <param name="onSearchCompleted">The on search completed.</param>
/// <param name="onError">The on error.</param>
public static void Search(string searchText, 
Action<IEnumerable<Twit>> onSearchCompleted = null, 
Action<Exception> onError = null, Action onFinally = null)
{
    WebClient webClient = new WebClient();

    // register on download complete event
    webClient.OpenReadCompleted += delegate(object sender, 
				OpenReadCompletedEventArgs e)
    {
        try
        {
            // report error
            if (e.Error != null)
            {
                if (onError != null)
                {
                    onError(e.Error);
                }
                return;
            }

            // convert json result to model
            Stream stream = e.Result;
            DataContractJsonSerializer dataContractJsonSerializer = 
			new DataContractJsonSerializer(typeof(TwitterResults));
            TwitterResults twitterResults = 
		(TwitterResults)dataContractJsonSerializer.ReadObject(stream);

            // notify completed callback
            if (onSearchCompleted != null)
            {
                onSearchCompleted(twitterResults.results);
            }
        }
        finally
        {
            // notify finally callback
            if (onFinally != null)
            {
                onFinally();
            }
        }
    };

    string encodedSearchText = HttpUtility.UrlEncode(searchText);
    webClient.OpenReadAsync(new Uri(string.Format
		(TwitterSearchQuery, encodedSearchText)));
}

使用 Twitter 搜索服务

使用该服务很简单

TwitterService.Search(
    textbox.Text,
   (items) => { listbox.ItemsSource = items; },
   (exception) => { MessageBox.Show(exception.Message); },
   null
   );

可以从 此处 下载示例应用程序。

注意:此代码最初作为 Microsoft 为我编写的 Windows Phone 开发者培训工具包中“使用 Pivot 和 Panorama 控件”实验室的一部分发布。

暂时就到这里,
Arik Poznanski。

© . All rights reserved.