WebClient alternative for windows 8?

旧街凉风 提交于 2019-12-19 08:13:43

问题


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);

after sending event;

   StringReader stream = new StringReader(e.Result)

   XmlReader reader = XmlReader.Create(stream);
   reader.ReadToFollowing("yweather:atmosphere");
   string humidty = reader.MoveToAttribute("humidity");

but in Windows 8 RT there is no such thing.

how can I fetch the following data? >http://weather.yahooapis.com/forecastrss?w=2343732&u=c


回答1:


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);
}

Simpler version would be just :

public async static Task<string> GetHttpResponse(string url)
{
    var client = new HttpClient();
    return await client.GetStringAsync(url);
}

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.

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



来源:https://stackoverflow.com/questions/15191984/webclient-alternative-for-windows-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!