在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命名空間。