Call Web API in WinForms: Step-by-Step Guide

In a WinForm application, you can commonly use the HttpClient class to send HTTP requests and receive responses when calling a web interface. Here is a simple example code:

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;
            }
        }
    }
}

In the example above, MainForm is a main window class of WinForm, which contains two buttons for retrieving data and sending data. HttpClient is initialized in the constructor and the base address of the Web API is set. When the buttons are clicked, corresponding HTTP requests are sent through HttpClient and the response content is handled. Make sure to include the namespaces System.Net.Http and System.Threading.Tasks.

bannerAds