我使用WebClient
来获取Windows Phone 8和Android的Yahoo数据
使用WebClient的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
答案 0 :(得分: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