Skip to content

Instantly share code, notes, and snippets.

@lucky-c
Created February 21, 2018 15:23
Show Gist options
  • Save lucky-c/656503bfe5d0adb382e0428072328d03 to your computer and use it in GitHub Desktop.
Save lucky-c/656503bfe5d0adb382e0428072328d03 to your computer and use it in GitHub Desktop.
Basic API Call for Xamarin.Forms
public class APIService
{
HttpClient client;
public APIService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
/// <summary>
/// Get all todo data from dummy API
/// </summary>
/// <returns></returns>
public async Task<List<TodoResponse>> GetAllToDo()
{
// Change to desired URL.
string restUrl = "https://jsonplaceholder.typicode.com/todos";
var uri = new Uri(restUrl);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<List<TodoResponse>>(content);
return result;
}
return null;
}
/// <summary>
/// Get all todo data from dummy API (Raw JSON format)
/// </summary>
/// <returns></returns>
public async Task<string> GetAllToDoRaw()
{
// Change to desired URL.
string restUrl = "https://jsonplaceholder.typicode.com/todos";
var uri = new Uri(restUrl);
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return content;
}
return null;
}
}
/// <summary>
/// JSON result as class
/// </summary>
public class TodoResponse
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public bool Completed { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment