.NET Documentation

HttpClient.GetAsync Method

Task<HttpResponseMessage> GetAsync(string requestUri)

Summary

Sends a GET request to the specified resource address as an asynchronous operation.

Description

This method is used to send an HTTP GET request to a specified URI. It's an asynchronous operation, meaning it won't block the calling thread while waiting for the response. This is crucial for maintaining responsiveness in applications, especially user interfaces.

The GetAsync method returns a Task object that represents the asynchronous operation. Once the operation completes, the task will contain a HttpResponseMessage object, which holds the server's response to the request.

You can use the overloaded versions of this method to specify an CancellationToken for aborting the request, or to include additional HTTP content in the request (though GET requests typically do not have a body).

Parameters

requestUri

System.String

The Uniform Resource Identifier (URI) to request.

Returns

Task<HttpResponseMessage>

A task object that represents the asynchronous operation. The Result property of the task object will contain a HttpResponseMessage describing the response to the request.

Exceptions

This method can throw exceptions, including:

  • ArgumentNullException: If requestUri is null.
  • HttpRequestException: If an error occurs during the request.
  • InvalidOperationException: If the HttpClient instance has been disposed.

Example


using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Example
{
    public static async Task MakeGetRequestAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                string url = "https://jsonplaceholder.typicode.com/todos/1";
                Console.WriteLine($"Sending GET request to: {url}");

                HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Response received:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                }
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"An error occurred: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"An unexpected error occurred: {e.Message}");
            }
        }
    }

    public static async Task Main(string[] args)
    {
        await MakeGetRequestAsync();
    }
}
                

See Also