🌐 Networking & APIs
HTTP Requests with HttpClient
GET, POST, EnsureSuccessStatusCode, timeouts, cancellation.

HttpClient — The Right Way

csharp
public interface IWeatherService
{
    Task<WeatherResponse> GetCurrentWeatherAsync(string city);
}

public class WeatherService(HttpClient http) : IWeatherService
{
    public async Task<WeatherResponse> GetCurrentWeatherAsync(string city)
    {
        var r = await http.GetAsync($"/weather?city={city}&units=metric");
        r.EnsureSuccessStatusCode();
        return await r.Content.ReadFromJsonAsync<WeatherResponse>();
    }
}

POST with JSON Body

csharp
var response = await http.PostAsync("/tasks", JsonContent.Create(taskDto));
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ApiResult>();

Timeouts & Cancellation

csharp
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
    var data = await GetCurrentWeatherAsync("London", cts.Token);
}
catch (OperationCanceledException)
{
    await Shell.Current.DisplayAlert("Timeout", "Request timed out.", "OK");
}

Key Takeaways

Register HttpClient via AddHttpClient() in MauiProgram.cs
ReadFromJsonAsync() deserializes JSON to your model type directly
EnsureSuccessStatusCode() throws on 4xx and 5xx HTTP errors
Use CancellationTokenSource to enforce a timeout on any network call
Lesson 21 of 30Networking & APIs
← Previous Next Lesson →