2013-03-03 14 views
5

Io uso WebClient per recuperare i dati di Yahoo per Windows Phone 8 e Android HttpClient Con WebClient posso fareAlternativa WebClient per Windows 8?

WebClient client = new WebClient(); 
    client.DownloadStringCompleted += new  DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
    client.DownloadStringAsync(url); 

dopo l'invio dell'evento;

StringReader stream = new StringReader(e.Result) 

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

ma in Windows 8 RT non esiste una cosa del genere.

come posso recuperare i seguenti dati? >http://weather.yahooapis.com/forecastrss?w=2343732&u=c

+0

Hai guardato a 'HttpClient'? –

risposta

8

è possibile utilizzare HttpClient classe, qualcosa di simile:

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

versione più semplice sarebbe solo:

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

Ma se si verifica http errore GetStringAsync getterà HttpResponseException, e per quanto io può vedere che non è indicato lo stato http tranne nel messaggio di eccezione.

UPDATE: non ho notato che in realtà si sta tentando di leggere feed RSS, non è necessario HttpClient e parser XML, basta utilizzare la classe SyndicationFeed, qui è l'esempio:

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh452994.aspx

+0

Oppure usa 'await client.GetStringASync' ... non è necessario controllare il codice di stato da soli. –

+0

Suppongo che GetStringASync genererà un'eccezione se fallisce (WebException)? Non c'è nulla nei documenti MSDN su quello –

+0

Bene, l'attività restituita da GetStringAsync si verificherà. Sono d'accordo che dovrebbe essere meglio documentato. –