How to download a webpage in MetroStyle app (WinRT) and C#
-
22-10-2019 - |
Question
I'm creating a MetroStyle app and I want to use a website API that is based on the HTTP Get methods. For instance to login I should download the XML returned by this URL:
websitehost.com/api/login.php?u=username&p=password
The problem is that the new MetroStyle apps won't let me to use many of the methods I've been using for years in .Net so how can I download the returned XML document and parse it?
Solution
You might be searching for this:
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();
}
OTHER TIPS
You can use either the Windows.Data.Xml.Dom.XmlDocument.LoadFromUriAsync(Uri)
method to automatically acquire and parse the XML, or you could manually use a Windows.Networking.BackgroundTransfer.DownloadOperation
instance to call the web service and acquire the data, and Windows.Data.Xml.Dom.XmlDocument.LoadXml(string)
to parse the data.
You should be able to use
var data = await (new System.Net.Http.HttpClient()).GetAsync(new Uri("http://wherever"));
And then do whatever you need with the data, including loading it with XmlDocument or XElement or whatnot.