Send HTTP Post request in Xamarin Forms C#

I use HttpClient. A simple example:

var client = new HttpClient();
client.BaseAddress = new Uri("localhost:8080");

string jsonData = @"{""username"" : ""myusername"", ""password"" : ""mypassword""}"

var content = new StringContent (jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("/foo/login", content);

// this result string should be something like: "{"token":"rgh2ghgdsfds"}"
var result = await response.Content.ReadAsStringAsync();

Where "/foo/login" will need to point to your HTTP resource. For example, if you have an AccountController with a Login method, then instead of "/foo/login" you would use something like "/Account/Login".

In general though, to handle the serializing and deserializing, I recommend using a tool like Json.Net.

As for the question about how it works, there is a lot going on here. If you have questions about how the async/await stuff works then I suggest you read Asynchronous Programming with Async and Await on MSDN


This should be fairly easy with HttpClient.

Something like this could work. However, you might need to proxy data from the device/simulator somehow to reach your server.

var client = new HttpClient();
var content = new StringContent(
    JsonConvert.SerializeObject(new { username = "myusername", password = "mypass" }));
var result = await client.PostAsync("localhost:8080", content).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
    var tokenJson = await result.Content.ReadAsStringAsync();
}

This code would probably go into a method with the following signature:

private async Task<string> Login(string username, string password)
{
    // code
}

Watch out using void instead of Task as return type. If you do that and any exception is thrown inside of the method that exception will not bubble out and it will go unhandled; that will cause the app to blow up. Best practice is only to use void when we are inside an event or similar. In those cases make sure to handle all possible exceptions properly.

Also the example above uses HttpClient from System.Net.HttpClient. Some PCL profiles does not include that. In those cases you need to add Microsoft's HttpClient library from Nuget. I also use JSON.Net (Newtonsoft.Json) to serialize the object with username and password.

I would also note that sending username and password in cleartext like this is not really recommended and should be done otherwise.

EDIT: If you are using .NET Standard on most of the versions you won't need to install System.Net.HttpClient from NuGet anymore, since it already comes with it.