我使用 WebClient
获取适用于 Windows Phone 8 和 Android 的 Yahoo 数据
HttpClient 和 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
最佳答案
你可以使用 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
关于c# - Windows 8 的 WebClient 替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191984/