在C#中,可以使用HttpClient类来发送带有form-data的HTTP请求。以下是一个简单的示例代码:
using System;using System.Net.Http;using System.Text;using System.Threading.Tasks;class Program{ static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { var formContent = new MultipartFormDataContent(); formContent.Add(new StringContent("value1"), "key1"); formContent.Add(new StringContent("value2"), "key2"); var response = await client.PostAsync("http://example.com/api", formContent); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } else { Console.WriteLine($"Error: {response.StatusCode}"); } } }}在上面的示例中,我们使用HttpClient类创建了一个HTTP POST请求,并添加了form-data内容。可以通过调用Add方法来向formContent中添加键值对数据。发送请求后,我们检查响应的状态码,如果请求成功,则读取响应内容并输出。