Windows 8 的 WebClient 替代方案? [英] WebClient alternative for windows 8?
问题描述
我使用 WebClient
为 Windows Phone 8 和 Android 获取雅虎数据HttpClient 和 WebClient 我可以做
I use WebClient
to fetch Yahoo data for Windows Phone 8 and Android
HttpClient With WebClient I can do
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 中没有这样的东西.
but in Windows 8 RT there is no such thing.
如何获取以下数据?>http://weather.yahooapis.com/forecastrss?w=2343732&u=c
推荐答案
您可以使用 HttpClient 类,如下所示:
You can use HttpClient class, something like this :
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 状态.
But if http error occurs GetStringAsync will throw HttpResponseException, and as far I can see there is no http status indicated except in exception message.
更新:我没有注意到您实际上是在尝试阅读 RSS Feed,您不需要 HttpClient 和 XML 解析器,只需使用 SyndicationFeed 类,示例如下:
UPDATE: I didn't noticed that you in fact you are trying to read RSS Feed, you don't need HttpClient and XML parser, just use SyndicationFeed class, here is the example :
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452994.aspx
这篇关于Windows 8 的 WebClient 替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!