2013-03-03 34 views
5

我用WebClient獲取用於Windows Phone的8和Android 的HttpClient隨着WebClient的雅虎數據發送事件後我能做的適用於Windows 8的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

+0

你看過'HttpClient'嗎? – 2013-03-03 23:04:36

回答

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訂閱,你並不需要的HttpClient和XML解析器,只需使用SyndicationFeed類,這裏是例子:

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

+0

或者使用'await client.GetStringASync' ...不需要自己檢查狀態碼。 – 2013-03-03 23:08:06

+0

我認爲GetStringASync如果失敗會拋出異常(WebException)?在MSDN文檔中沒有任何關於該 – 2013-03-03 23:14:26

+0

嗯,由GetStringAsync返回的任務將會出錯。我同意它應該更好地記錄。 – 2013-03-04 07:38:14

相關問題