使用HttpClient 发送请求基本实例
演示如何发送 GET 请求和 POST 请求:
using System;
using System.Net.Http;
using System.Threading.Tasks;class Program
{static async Task Main(string[] args){await SendGetRequest();await SendPostRequest();}static async Task SendGetRequest(){using (HttpClient client = new HttpClient()){try{HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");response.EnsureSuccessStatusCode();string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine(responseBody);}catch (HttpRequestException ex){Console.WriteLine($"Error: {ex.Message}");}}}static async Task SendPostRequest(){using (HttpClient client = new HttpClient()){try{var postData = new FormUrlEncodedContent(new[]{new KeyValuePair<string, string>("key1", "value1"),new KeyValuePair<string, string>("key2", "value2")});HttpResponseMessage response = await client.PostAsync("https://api.example.com/endpoint", postData);response.EnsureSuccessStatusCode();string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine(responseBody);}catch (HttpRequestException ex){Console.WriteLine($"Error: {ex.Message}");}}}
}
发送带参数的 请求时 可以使用UriBuilder 类来构造
using System;
using System.Net.Http;
using System.Threading.Tasks;class Program
{static async Task Main(string[] args){await SendGetRequestWithParams();}static async Task SendGetRequestWithParams(){using (HttpClient client = new HttpClient()){try{var builder = new UriBuilder("https://api.example.com/data");builder.Query = "param1=value1¶m2=value2";HttpResponseMessage response = await client.GetAsync(builder.Uri);response.EnsureSuccessStatusCode();string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine(responseBody);}catch (HttpRequestException ex){Console.WriteLine($"Error: {ex.Message}");}}}
}
你可以根据需要添加或删除查询参数。然后,我们将 UriBuilder.Uri 属性传递给 HttpClient.GetAsync 方法来发送 GET 请求。在响应中,我们读取响应正文并打印到控制台上。