在WinForm应用程序中调用Web接口,一般可以使用HttpClient类来发送HTTP请求并接收响应。以下是一个简单的示例代码:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace WinFormWebApiExample
{
public partial class MainForm : Form
{
private HttpClient httpClient;
public MainForm()
{
InitializeComponent();
// 初始化HttpClient
httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://api.example.com"); // 设置Web接口的基础地址
}
private async void btnGetData_Click(object sender, EventArgs e)
{
try
{
// 发送GET请求,并获取响应内容
HttpResponseMessage response = await httpClient.GetAsync("/api/data");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// 处理响应内容
// ...
// 显示结果
tbResult.Text = responseBody;
}
catch (Exception ex)
{
tbResult.Text = "Error: " + ex.Message;
}
}
private async void btnSendData_Click(object sender, EventArgs e)
{
try
{
// 构造要发送的数据
var data = new { Name = tbName.Text, Age = int.Parse(tbAge.Text) };
// 发送POST请求,并获取响应内容
HttpResponseMessage response = await httpClient.PostAsJsonAsync("/api/data", data);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// 处理响应内容
// ...
// 显示结果
tbResult.Text = responseBody;
}
catch (Exception ex)
{
tbResult.Text = "Error: " + ex.Message;
}
}
}
}
```
在上面的示例中,MainForm是一个WinForm的主窗体类,其中有两个按钮分别用于获取数据和发送数据。在构造函数中初始化HttpClient并设置Web接口的基础地址。点击按钮时,通过HttpClient发送对应的HTTP请求并处理响应内容。注意要引入System.Net.Http和System.Threading.Tasks命名空间。