httpclient google in csharp

Here's a code snippet that shows how to use HttpClient to execute a GET request against Google's search API:

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

public class Program
{
    public static async Task Main(string[] args)
    {
        var queryString = "q=hello+world"; // Example query string
        var baseUrl = "https://www.googleapis.com/customsearch/v1"; // API endpoint

        using var client = new HttpClient();
        var response = await client.GetAsync($"{baseUrl}?{queryString}");
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}
537 chars
18 lines

In the above example, we're using HttpClient to execute a GET request against the Google Custom Search API endpoint. We're passing a simple query string as the queryString variable and appending it to the baseUrl. We then use HttpClient to send the GET request and await a response. Finally, we read the response body and print it to the console.

Note that in a real-world application, you would typically handle errors and exceptions, configure HttpClient with custom settings, and deserialize the response body to a strongly typed object.

gistlibby LogSnag