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.