C#实现的全能HTTP POST工具类

简介: C#实现的全能HTTP POST工具类,整合了多种协议格式、安全认证和扩展能力,支持JSON、表单、文件上传等场景

C#实现的全能HTTP POST工具类,整合了多种协议格式、安全认证和扩展能力,支持JSON、表单、文件上传等场景:


一、核心工具类实现

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class HttpPostHelper
{
   
    private readonly HttpClient _httpClient;
    private readonly Dictionary<string, string> _defaultHeaders = new();

    public HttpPostHelper()
    {
   
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.ExpectContinue = false;
        _httpClient.DefaultRequestHeaders.ConnectionClose = true;
    }

    // 添加全局Header
    public void AddHeader(string key, string value)
    {
   
        _defaultHeaders[key] = value;
    }

    // 基础POST方法(同步)
    public string Post(string url, 
                      object data = null,
                      ContentType contentType = ContentType.Json,
                      string token = null,
                      Encoding encoding = null)
    {
   
        var request = CreateRequest(url, HttpMethod.Post, data, contentType, token);
        return ExecuteRequest(request);
    }

    // 基础POST方法(异步)
    public async Task<string> PostAsync(string url,
                                       object data = null,
                                       ContentType contentType = ContentType.Json,
                                       string token = null,
                                       Encoding encoding = null)
    {
   
        var request = CreateRequest(url, HttpMethod.Post, data, contentType, token);
        return await ExecuteRequestAsync(request);
    }

    // 文件上传
    public async Task<HttpResponseMessage> UploadFile(string url,
                                                     string filePath,
                                                     string fieldName = "file",
                                                     object formData = null)
    {
   
        using var content = new MultipartFormDataContent();
        var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");

        content.Add(fileContent, fieldName, Path.GetFileName(filePath));

        if (formData != null)
        {
   
            foreach (var prop in formData.GetType().GetProperties())
            {
   
                content.Add(new StringContent(prop.GetValue(formData)?.ToString() ?? ""),
                           prop.Name);
            }
        }

        var response = await _httpClient.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        return response;
    }

    private HttpRequestMessage CreateRequest(string url,
                                            HttpMethod method,
                                            object data,
                                            ContentType contentType,
                                            string token)
    {
   
        var request = new HttpRequestMessage(method, url);

        // 设置认证信息
        if (!string.IsNullOrEmpty(token))
        {
   
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }

        // 合并Headers
        foreach (var header in _defaultHeaders)
        {
   
            request.Headers.Add(header.Key, header.Value);
        }

        // 处理请求体
        if (data != null)
        {
   
            var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8);
            content.Headers.ContentType = MediaTypeHeaderValue.Parse($"application/{contentType}");
            request.Content = content;
        }

        return request;
    }

    private string ExecuteRequest(HttpRequestMessage request)
    {
   
        try
        {
   
            var response = _httpClient.Send(request);
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsStringAsync().Result;
        }
        catch (HttpRequestException ex)
        {
   
            HandleHttpRequestException(ex);
            return null;
        }
    }

    private async Task<string> ExecuteRequestAsync(HttpRequestMessage request)
    {
   
        try
        {
   
            var response = await _httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
        catch (HttpRequestException ex)
        {
   
            await HandleHttpRequestExceptionAsync(ex);
            return null;
        }
    }

    private void HandleHttpRequestException(HttpRequestException ex)
    {
   
        // 实现自定义异常处理逻辑
        Console.WriteLine($"HTTP请求失败: {ex.Message}");
    }

    private async Task HandleHttpRequestExceptionAsync(HttpRequestException ex)
    {
   
        // 实现异步异常处理逻辑
        await Task.Run(() => Console.WriteLine($"HTTP请求失败: {ex.Message}"));
    }
}

public enum ContentType
{
   
    Json,
    FormUrlEncoded,
    MultipartFormData
}

二、核心功能说明

1. 多协议格式支持

// JSON格式
var json = new {
    Name = "Test", Age = 30 };
string response = helper.Post("https://api.example.com", json, ContentType.Json);

// 表单格式
var formData = new {
    Username = "user", Password = "123456" };
string formResponse = helper.Post("https://api.example.com/login", formData, ContentType.FormUrlEncoded);

// 文件上传
await helper.UploadFile("https://api.example.com/upload", "test.txt", "file", new {
    description = "测试文件" });

2. 安全认证机制

// 添加Bearer Token
helper.AddHeader("Authorization", "Bearer your_token_here");

// 添加自定义认证头
helper.AddHeader("X-Api-Key", "your_api_key");

3. 高级配置选项

// 配置超时时间
helper._httpClient.Timeout = TimeSpan.FromSeconds(30);

// 禁用SSL验证(仅测试环境使用)
helper._httpClient.DefaultRequestHeaders.Add("Unsafe-SSL", "true");

三、扩展功能实现

1. 自定义序列化

public class CustomSerializer
{
   
    public static string Serialize(object obj)
    {
   
        // 使用System.Text.Json
        return JsonSerializer.Serialize(obj);

        // 或使用XmlSerializer
        // var serializer = new XmlSerializer(obj.GetType());
        // using var writer = new StringWriter();
        // serializer.Serialize(writer, obj);
        // return writer.ToString();
    }
}

// 扩展HttpHelper
public static class HttpPostHelperExtensions
{
   
    public static string PostWithCustomSerializer(this HttpPostHelper helper, 
                                                 string url, 
                                                 object data,
                                                 ContentType contentType)
    {
   
        var content = new StringContent(CustomSerializer.Serialize(data), Encoding.UTF8);
        content.Headers.ContentType = MediaTypeHeaderValue.Parse($"application/{contentType}");
        return helper.Post(url, data, contentType);
    }
}

2. 自动重试机制

public static class RetryPolicy
{
   
    public static async Task<string> WithRetry(this HttpPostHelper helper, 
                                               string url, 
                                               Func<Task<string>> action,
                                               int maxRetries = 3)
    {
   
        int attempt = 0;
        Exception lastException = null;

        do
        {
   
            try
            {
   
                return await action();
            }
            catch (Exception ex)
            {
   
                lastException = ex;
                attempt++;
                await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
            }
        } while (attempt < maxRetries);

        throw new Exception($"请求失败,已尝试 {maxRetries} 次", lastException);
    }
}

// 使用示例
var result = await helper.WithRetry("https://api.example.com", 
                                   () => helper.PostAsync("data", retryCount: 5));

四、工程实践建议

1. 配置管理

public class HttpConfig
{
   
    public string BaseUrl {
    get; set; }
    public int TimeoutSeconds {
    get; set; } = 30;
    public bool EnableLogging {
    get; set; } = true;
}

// 初始化工具类
var config = new HttpConfig
{
   
    BaseUrl = "https://api.example.com",
    TimeoutSeconds = 60
};

var httpClient = new HttpClient
{
   
    BaseAddress = new Uri(config.BaseUrl),
    Timeout = TimeSpan.FromSeconds(config.TimeoutSeconds)
};

2. 日志记录

public static class Logger
{
   
    public static void LogRequest(string method, string url, object data)
    {
   
        var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] " +
                         $"{method} {url}\n" +
                         $"Data: {JsonConvert.SerializeObject(data)}";
        File.AppendAllText("http.log", logMessage + Environment.NewLine);
    }
}

// 在HttpHelper中添加日志
public HttpRequestMessage CreateRequest(string url, HttpMethod method, object data, ContentType contentType, string token)
{
   
    Logger.LogRequest(method.ToString(), url, data);
    // ...原有逻辑
}

五、使用示例

var helper = new HttpPostHelper();
helper.AddHeader("X-Custom-Header", "CustomValue");

// 同步请求
var response = helper.Post("https://api.example.com/data", 
                          new {
    Id = 1, Name = "Test" },
                          ContentType.FormUrlEncoded,
                          token: "your_token");

// 异步请求
await helper.PostAsync("https://api.example.com/upload", 
                      new {
    File = "test.pdf" },
                      ContentType.MultipartFormData);

// 文件上传
var uploadResponse = await helper.UploadFile(
    "https://api.example.com/upload",
    @"C:\files\document.pdf",
    "document",
    new {
    description = "季度报告", projectId = 1001 }
);

参考代码 Http的POST万能工具 www.youwenfan.com/contentalg/93248.html

六、扩展建议

  1. 拦截器模式:实现请求/响应拦截器,统一处理认证、日志、缓存
  2. 连接池管理:优化HttpClient连接复用策略
  3. OAuth2支持:集成令牌自动刷新机制
  4. 性能监控:添加请求耗时统计和性能分析
  5. 测试套件:使用xUnit编写单元测试和集成测试
相关文章
|
7天前
|
数据采集 人工智能 安全
|
16天前
|
云安全 监控 安全
|
2天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:七十、小树成林,聚沙成塔:随机森林与大模型的协同进化
随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并结合它们的预测结果来提高准确性和稳定性。其核心思想包括两个随机性:Bootstrap采样(每棵树使用不同的训练子集)和特征随机选择(每棵树分裂时只考虑部分特征)。这种方法能有效处理大规模高维数据,避免过拟合,并评估特征重要性。随机森林的超参数如树的数量、最大深度等可通过网格搜索优化。该算法兼具强大预测能力和工程化优势,是机器学习中的常用基础模型。
267 156
|
3天前
|
机器学习/深度学习 人工智能 前端开发
构建AI智能体:六十九、Bootstrap采样在大模型评估中的应用:从置信区间到模型稳定性
Bootstrap采样是一种通过有放回重抽样来评估模型性能的统计方法。它通过从原始数据集中随机抽取样本形成多个Bootstrap数据集,计算统计量(如均值、标准差)的分布,适用于小样本和非参数场景。该方法能估计标准误、构建置信区间,并量化模型不确定性,但对计算资源要求较高。Bootstrap特别适合评估大模型的泛化能力和稳定性,在集成学习、假设检验等领域也有广泛应用。与传统方法相比,Bootstrap不依赖分布假设,在非正态数据中表现更稳健。
206 105
|
10天前
|
SQL 自然语言处理 调度
Agent Skills 的一次工程实践
**本文采用 Agent Skills 实现整体智能体**,开发框架采用 AgentScope,模型使用 **qwen3-max**。Agent Skills 是 Anthropic 新推出的一种有别于mcp server的一种开发方式,用于为 AI **引入可共享的专业技能**。经验封装到**可发现、可复用的能力单元**中,每个技能以文件夹形式存在,包含特定任务的指导性说明(SKILL.md 文件)、脚本代码和资源等 。大模型可以根据需要动态加载这些技能,从而扩展自身的功能。目前不少国内外的一些框架也开始支持此种的开发方式,详细介绍如下。
729 5
|
13天前
|
人工智能 自然语言处理 API
一句话生成拓扑图!AI+Draw.io 封神开源组合,工具让你的效率爆炸
一句话生成拓扑图!next-ai-draw-io 结合 AI 与 Draw.io,通过自然语言秒出架构图,支持私有部署、免费大模型接口,彻底解放生产力,绘图效率直接爆炸。
817 153