Xamarin Forms PCL - Clean and easy way for web request?
I am creating a xamarin Android / iOS app with a portable class library. I'm looking for the best way to do this example in a PCL project:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create (
"http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
//do something with the response string
// Clean up the streams and the response.
reader.Close ();
response.Close ();
}
}
}
+3
source to share
2 answers
Just use this NuGet package instead of https://www.nuget.org/packages/Microsoft.Net.Http It implements the PCL HTTP request plus it supports async.
EDIT Sample produced from Hansleman website.
public static async Task<HttpResponseMessage> GetTheGoodStuff() { var httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://hanselman.com/blog/"); var response = await httpClient.SendAsync(request); return response; }
+5
source to share
Flurl.Http (disclaimer: I'm the author) is a Xamarin compatible PCL that makes this thing really simple:
string s = await "http://www.contoso.com/default.html".GetStringAsync();
Get it on NuGet .
+5
source to share