5

我用来WebClient为 Windows Phone 8 和 Android HttpClient 获取 Yahoo 数据 使用 WebClient 我可以做到

 WebClient client = new WebClient();
   client.DownloadStringCompleted += new     DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(url);

发送事件后;

   StringReader stream = new StringReader(e.Result)

   XmlReader reader = XmlReader.Create(stream);
   reader.ReadToFollowing("yweather:atmosphere");
   string humidty = reader.MoveToAttribute("humidity");

但在 Windows 8 RT 中没有这样的东西。

如何获取以下数据?> http://weather.yahooapis.com/forecastrss?w=2343732&u=c

4

1 回答 1

8

您可以使用 HttpClient 类,如下所示:

public async static Task<string> GetHttpResponse(string url)
{
    var request = new HttpRequestMessage(HttpMethod.Get, url);
    request.Headers.Add("UserAgent", "Windows 8 app client");

    var client = new HttpClient();
    var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

    if (response.IsSuccessStatusCode)
      return await response.Content.ReadAsStringAsync();
    else
     throw new Exception("Error connecting to " + url +" ! Status: " + response.StatusCode);
}

更简单的版本就是:

public async static Task<string> GetHttpResponse(string url)
{
    var client = new HttpClient();
    return await client.GetStringAsync(url);
}

但是如果发生 http 错误,GetStringAsync 将抛出 HttpResponseException,并且据我所知,除了异常消息中没有指示 http 状态。

更新:我没有注意到您实际上正在尝试阅读 RSS Feed,您不需要 HttpClient 和 XML 解析器,只需使用 SyndicationFeed 类,这是示例:

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452994.aspx

于 2013-03-03T23:04:39.310 回答