Windows 8有哪些WebClient的替代方案?

5
我使用WebClient在Windows Phone 8和Android上获取Yahoo数据,而HttpClient则可以实现同样的功能。
 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


你看过 HttpClient 吗? - Davin Tryon
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


或者使用 await client.GetStringASync... 没有必要自己检查状态码。 - Jon Skeet
我猜测如果GetStringASync失败了(WebException),它会抛出异常?MSDN文档中没有提到这一点。 - Antonio Bakula
好的,GetStringAsync 返回的任务会出错。我同意它应该有更好的文档记录。 - Jon Skeet
WinRT上没有WebClient类,你应该使用XDocument并解析上面GetHttpResponse方法返回的字符串,如果内容当然是XML。 - Antonio Bakula
我没有注意到你想要阅读RSS源,看看这个例子http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452994.aspx - Antonio Bakula
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接