Your Own Client
So far, you've only used a premade client to consume a Web API. However, for less popular APIs, there will not be any client for you to use. In those cases, you will have to make HTTP calls yourself. In .NET, the way of making calls has evolved quite a lot. If you don't want any third-party libraries, you can use the HttpClient
class.
HttpClient
In this section, you'll repeat the GitHub Users
example (from the Postman section), but this time using HttpClient
. The flow for this is quite simple and is described for you in detail in the following example:
- Within the
GitHttp
static class, create theGetUser
method:public static async Task GetUser()
- Within the
GitExamples
method, first, create a client:client = new HttpClient { BaseAddress = new Uri("https://api.github.com") }; client.DefaultRequestHeaders.Add("User-Agent", "Packt");
Creating a client almost always involves specifying a specific base URL...