var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts"); var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content);
var client = new HttpClient(); var content = new StringContent("{\"name\":\"John\",\"age\":30}", Encoding.UTF8, "application/json"); var request = new HttpRequestMessage(HttpMethod.Post, "https://example.com/api/users"); request.Content = content; var response = await client.SendAsync(request); var result = await response.Content.ReadAsStringAsync(); Console.WriteLine(result);In this example, we are using the HttpClient class to send an HTTP POST request to the web server at example.com and create a new user. We create a new instance of the StringContent class and pass in a JSON string that represents the user object. We also specify the encoding and content type of the request. We then create a new instance of the HttpRequestMessage class and pass in the HTTP method and the URL of the API endpoint. We set the content of the request to the StringContent object we created earlier. Finally, we send the request using the SendAsync() method of the HttpClient class and await the response. We use the ReadAsStringAsync() method to retrieve the content of the response as a string and print it to the console. Package library: System.Net.Http.