I'm having a stab at some mobile development with Xamarin and C#. I'm building a simple login screen for an Android app and I'm using the HttpClient to make the actual calls but I'm stuck on some of the details to get it to work.
I have set up a simple Client class that represents my API client:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Acme.Api
{
public class Session
{
public string Token;
public int Timeout;
}
public class Client
{
public async Task<string> authenticate( string username, string password )
{
using (var client = new HttpClient ())
{
string content = null;
client.BaseAddress = new Uri ("https://example.com/api/");
client.DefaultRequestHeaders.Accept.Clear ();
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Basic", string.Format ("{0}:{1}", username, password));
HttpResponseMessage response = await client.PostAsync ("auth", null);
content = await response.Content.ReadAsStringAsync();
return content;
}
}
}
}
As you can see, the authenticate method uses a POST to create a new session on the server. The /auth endpoint returns a JSON blob with a token and a timeout value.
This is how the authenticate method is called:
Client myClient = new Client();
Task<string> contentTask = myClient.authenticate( username, password );
var content = contentTask.ToString();
Console.Out.WriteLine(content);
My content never outputs anything. I'm obviously (and without a doubt) doing various things wrong.
How can I have my authenticate method return the JSON string I expect?
I have been using these sources for inspiration:
http://developer.xamarin.com/guides/cross-platform/advanced/async_support_overview/ http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client