WebClient替代Windows 8?

我使用WebClient获取Windows Phone 8的Yahoo数据,使用WebClient获取Android 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类,就像这样:

 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