2011-11-28 46 views
2

我正在創建一個MetroStyle應用程序,我想使用基於HTTP Get方法的網站API。比如登錄我應該下載這個URL返回的XML:如何下載MetroStyle應用程序(WinRT)和C#中的網頁

websitehost.com/api/login.php?u=username&p=password

的問題是,新的MetroStyle應用程序不會讓我使用了許多我在多年使用方法.net,那麼我怎樣才能下載返回的XML文檔並解析它?

+0

哇,這是一個不好的API。 –

+0

好吧,我簡化了它,但它基本上是這樣的。 –

+0

您不應該通過網址傳遞用戶名和密碼。 – McKay

回答

5

你可能會尋找這樣的:

public async Task<string> DownloadPageStringAsync(string url) 
    { 
     HttpClientHandler handler = new HttpClientHandler() 
     { UseDefaultCredentials = true, AllowAutoRedirect = true }; 

     HttpClient client = new HttpClient(handler); 
     HttpResponseMessage response = await client.GetAsync(url); 
     response.EnsureSuccessStatusCode(); 
     return await response.Content.ReadAsStringAsync(); 
    } 
+0

是的,這是我用過的代碼,它能正常工作。我已經發布了這個地方,但我似乎無法找到鏈接。謝謝回覆。由於我已經測試過了,我會將其設置爲答案。 –

3

您可以使用Windows.Data.Xml.Dom.XmlDocument.LoadFromUriAsync(Uri)方法自動獲取並解析XML,也可以手動使用Windows.Networking.BackgroundTransfer.DownloadOperation實例調用Web服務並獲取數據,使用Windows.Data.Xml.Dom.XmlDocument.LoadXml(string)解析數據。

+0

您能否解釋一下我如何使用'DownloadOperation'? –

+0

我很想看看如何下載XML文件以外的文件。 –

+0

沒有太多的例子,但我可以冒險猜測你可以通過調用['BackgroundDownloader.StartDownloadAsync(Uri,IStorageFile)'](http://msdn.microsoft.com/zh-cn/library/default.aspx)來獲得'DownloadOperation'的實例。 COM/EN-US /庫/窗/應用/ windows.networking.backgroundtransfer.backgrounddownloader.startdownloadasync)。 –

0

您應該能夠使用

var data = await (new System.Net.Http.HttpClient()).GetAsync(new Uri("http://wherever")); 

然後做任何你需要的數據,包括與XmlDocument的或的XElement或諸如此類的東西加載它。

相關問題