阅读量:0
在C#中创建一个HTTP客户端可以使用HttpClient
类。下面是一个简单的示例代码:
using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main() { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1"); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine("Request failed with status code: " + response.StatusCode); } } } }
在上面的代码中,我们创建了一个HttpClient
对象,然后通过调用GetAsync
方法来发送一个GET请求,并且等待响应。如果响应状态码为成功,则打印出响应体的内容,否则打印出请求失败的状态码。