文章的目的为了记录使用C# 开发学习的经历。开发流程和要点有些记忆模糊,赶紧记录,防止忘记。
相关链接:
推荐链接:
开源 C# .net mvc 开发(一)WEB搭建_c#部署web程序-CSDN博客
开源 C# .net mvc 开发(二)网站快速搭建_c#网站开发-CSDN博客
开源 C# .net mvc 开发(三)WEB内外网访问-CSDN博客
开源 C# .net mvc 开发(四)工程结构、页面提交以及显示-CSDN博客
开源 C# .net mvc 开发(五)常用代码快速开发_c# mvc开发-CSDN博客
开源 C# .net mvc 开发(六)发送邮件、定时以及CMD编程-CSDN博客
开源 C# .net mvc 开发(七)动态图片、动态表格和json数据生成-CSDN博客
开源 C# .net mvc 开发(八)IIS Express轻量化Web服务器的配置和使用-CSDN博客
开源 C# .net mvc 开发(九)websocket--服务器与客户端的实时通信-CSDN博客
本章节主要内容是:HTTP 客户端示例,使用 WinForms 异步编程和 HTTP 请求处理。
目录:
1.源码分析
2.所有源码
3.效果演示
一、源码分析1. 命名空间和引用分析
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http; // HTTP客户端功能
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; // WinForms UI组件
namespace _9_http
{
// 主窗体类
public partial class Form1 : Form
作用:引入了必要的命名空间,特别是:
System.Net.Http:提供HttpClient等HTTP功能
System.Windows.Forms:提供WinForms UI组件
-
类成员变量声明
private TextBox txtUrl; // URL输入框
private TextBox txtResult; // 结果显示框
private Button btnGet; // GET请求按钮
private Button btnPost; // POST请求按钮
private HttpClient httpClient; // HTTP客户端实例
作用:声明了窗体所需的UI组件和HTTP客户端实例。 -
构造函数分析
3.1 主要构造函数
功能:
初始化窗体组件
创建HttpClient单例
设置User-Agent头避免被网站拒绝
public Form1()
{
InitializeComponent(); // 初始化设计器生成的组件
init(); // 调用自定义初始化方法
httpClient = new HttpClient(); // 创建HttpClient实例
// 设置默认请求头(伪装浏览器)
httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
}
3.2 初始化方法 init()
private void init()
{
// URL输入框初始化
txtUrl = new TextBox();
txtUrl.Text = "https://www.hao123.com/"; // 默认URL
txtUrl.Location = new System.Drawing.Point(12, 12); // 位置
txtUrl.Size = new System.Drawing.Size(400, 23); // 尺寸
// 结果文本框初始化
txtResult = new TextBox();
txtResult.Multiline = true; // 多行模式
txtResult.ScrollBars = ScrollBars.Both; // 水平和垂直滚动条
txtResult.Location = new System.Drawing.Point(12, 45);
txtResult.Size = new System.Drawing.Size(600, 300);
txtResult.WordWrap = false; // 禁用自动换行
// GET按钮初始化
btnGet = new Button();
btnGet.Text = "GET请求";
btnGet.Location = new System.Drawing.Point(420, 11);
btnGet.Size = new System.Drawing.Size(80, 25);
btnGet.Click += BtnGet_Click; // 绑定点击事件
// POST按钮初始化
btnPost = new Button();
btnPost.Text = "POST请求";
btnPost.Location = new System.Drawing.Point(510, 11);
btnPost.Size = new System.Drawing.Size(80, 25);
btnPost.Click += BtnPost_Click; // 绑定点击事件
// 窗体设置
this.Text = "HTTP请求示例"; // 窗体标题
this.ClientSize = new System.Drawing.Size(624, 361); // 窗体尺寸
this.Controls.AddRange(new Control[] { txtUrl, txtResult, btnGet, btnPost });
}
- GET请求处理函数 BtnGet_Click
执行流程:
输入验证 → 显示状态 → 设置超时 → 发送请求 → 检查状态 → 读取内容 → 格式化显示
private async void BtnGet_Click(object sender, EventArgs e)
{
// 1. URL验证
if (string.IsNullOrWhiteSpace(txtUrl.Text))
{
MessageBox.Show("请输入URL");
return;
}
try
{
// 2. 显示请求状态
txtResult.Text = "请求中...";
// 3. 设置超时时间(30秒)
httpClient.Timeout = TimeSpan.FromSeconds(30);
// 4. 发送异步GET请求(核心代码)
HttpResponseMessage response = await httpClient.GetAsync(txtUrl.Text);
// 5. 检查HTTP状态码(非2xx会抛出异常)
response.EnsureSuccessStatusCode();
// 6. 读取响应内容
string content = await response.Content.ReadAsStringAsync();
// 7. 格式化并显示结果
txtResult.Text = FormatResponse(response, content);
}
catch (HttpRequestException ex) // HTTP相关异常
{
txtResult.Text = $"HTTP错误: {ex.Message}";
}
catch (TaskCanceledException) // 超时异常
{
txtResult.Text = "请求超时";
}
catch (Exception ex) // 其他异常
{
txtResult.Text = $"错误: {ex.Message}";
}
}
- POST请求处理函数 BtnPost_Click
POST数据细节:
内容:{"key":"value"}
编码:UTF-8
内容类型:application/json
private async void BtnPost_Click(object sender, EventArgs e)
{
// 1. URL验证
if (string.IsNullOrWhiteSpace(txtUrl.Text))
{
MessageBox.Show("请输入URL");
return;
}
try
{
// 2. 显示请求状态
txtResult.Text = "请求中...";
// 3. 创建POST数据(固定JSON格式)
var postData = new StringContent("{\"key\":\"value\"}",
System.Text.Encoding.UTF8, "application/json");
// 4. 发送异步POST请求
HttpResponseMessage response = await httpClient.PostAsync(txtUrl.Text, postData);
// 5. 检查HTTP状态码
response.EnsureSuccessStatusCode();
// 6. 读取响应内容
string content = await response.Content.ReadAsStringAsync();
// 7. 格式化并显示结果
txtResult.Text = FormatResponse(response, content);
}
catch (Exception ex) // 统一异常处理
{
txtResult.Text = $"错误: {ex.Message}";
}
}
-
响应格式化函数 FormatResponse
private string FormatResponse(HttpResponseMessage response, string content)
{
return "状态码: {(int)response.StatusCode} {response.StatusCode}\n" + "响应头:\n{response.Headers}\n\n" +
$"响应内容:\n{content}";
}
输出格式:
状态码: 200 OK
响应头:
HeaderName1: Value1
HeaderName2: Value2
响应内容:
<html>...网页内容...</html>
二、所有源码
Form1.designer.cs界面文件
namespace _9_http
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1219, 974);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.TextBox txtPwd;
}
}
Form1.cs文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _9_http
{
public partial class Form1 : Form
{
/*
public Form1()
{
InitializeComponent();
}
*/
private TextBox txtUrl;
private TextBox txtResult;
private Button btnGet;
private Button btnPost;
private HttpClient httpClient;
public Form1()
{
InitializeComponent();
init();
httpClient = new HttpClient();
// 设置默认请求头(可选)
httpClient.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
}
private void init()
{
// URL输入框
txtUrl = new TextBox();
txtUrl.Text = "https://www.hao123.com/";
txtUrl.Location = new System.Drawing.Point(12, 12);
txtUrl.Size = new System.Drawing.Size(400, 23);
// 结果文本框
txtResult = new TextBox();
txtResult.Multiline = true;
txtResult.ScrollBars = ScrollBars.Both;
txtResult.Location = new System.Drawing.Point(12, 45);
txtResult.Size = new System.Drawing.Size(600, 300);
txtResult.WordWrap = false;
// 按钮
btnGet = new Button();
btnGet.Text = "GET请求";
btnGet.Location = new System.Drawing.Point(420, 11);
btnGet.Size = new System.Drawing.Size(80, 25);
btnGet.Click += BtnGet_Click;
btnPost = new Button();
btnPost.Text = "POST请求";
btnPost.Location = new System.Drawing.Point(510, 11);
btnPost.Size = new System.Drawing.Size(80, 25);
btnPost.Click += BtnPost_Click;
// 窗体设置
this.Text = "HTTP请求示例";
this.ClientSize = new System.Drawing.Size(624, 361);
this.Controls.AddRange(new Control[] { txtUrl, txtResult, btnGet, btnPost });
}
private async void BtnGet_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtUrl.Text))
{
MessageBox.Show("请输入URL");
return;
}
try
{
txtResult.Text = "请求中...";
// 设置超时时间
httpClient.Timeout = TimeSpan.FromSeconds(30);
HttpResponseMessage response = await httpClient.GetAsync(txtUrl.Text);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
txtResult.Text = FormatResponse(response, content);
}
catch (HttpRequestException ex)
{
txtResult.Text = $"HTTP错误: {ex.Message}";
}
catch (TaskCanceledException)
{
txtResult.Text = "请求超时";
}
catch (Exception ex)
{
txtResult.Text = $"错误: {ex.Message}";
}
}
private async void BtnPost_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtUrl.Text))
{
MessageBox.Show("请输入URL");
return;
}
try
{
txtResult.Text = "请求中...";
// 创建POST内容
var postData = new StringContent("{\"key\":\"value\"}",
System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(txtUrl.Text, postData);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
txtResult.Text = FormatResponse(response, content);
}
catch (Exception ex)
{
txtResult.Text = $"错误: {ex.Message}";
}
}
private string FormatResponse(HttpResponseMessage response, string content)
{
return $"状态码: {(int)response.StatusCode} {response.StatusCode}\n" +
$"响应头:\n{response.Headers}\n\n" +
$"响应内容:\n{content}";
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
httpClient?.Dispose();
base.OnFormClosing(e);
}
}
}
三、效果演示
输入https://www.hao123.com/,点击Post请求,可以获得hao123网址的回应。
