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编写单元测试和集成测试
相关文章
|
30天前
|
JSON C# 数据格式
C# 实现简单的 HTTP 请求工具(POST 补充)
该代码实现了一个基于 HttpClient 的异步 HTTP POST 请求工具类,支持以 JSON 格式提交数据并反序列化响应结果,具备异常处理机制,适用于 .NET 环境下的轻量级网络请求操作。
|
网络协议 API C#
C# 中模拟 POST 和 GET 请求的原理与实践
【1月更文挑战第4天】在现代网络应用中,HTTP请求是客户端与服务器交互的基础。其中,GET和POST是最常用的两种请求方法。本文将介绍如何使用C#语言模拟这两种请求,并解释其背后的工作原理。我们将利用.NET框架中的HttpClient类来发送请求,并处理服务器的响应。通过本文,读者将能够理解HTTP请求的基本构成,学会在C#中编写代码来模拟这些请求,进而在开发过程中实现与Web服务的交互。
|
JavaScript
vue使用iconfont图标
vue使用iconfont图标
439 1
|
30天前
|
JSON API C#
C# 实现简单的 HTTP 请求工具(GET/POST)
HTTP请求工具用于调用第三方API,支持GET和POST方法,实现数据获取与提交。示例代码展示通过HttpClient发送异步POST请求,处理响应并解析JSON结果,适用于高效集成外部服务。
|
9月前
|
存储 NoSQL MongoDB
阿里云MongoDB 8.0最新发布
MongoDB 8.0 在性能优化、工作负载管理、数据库扩展、安全性增强及向量搜索能力等方面实现了多项突破。新版本大幅提升主从复制效率,降低延迟,并支持灵活的分片迁移与在线重分片。同时,新增 query shape 和持久化索引过滤器功能,帮助用户精细化管理高并发场景。此外,社区版引入全文与向量搜索,助力 AI 应用开发。阿里云作为国内首家支持 MongoDB 8.0 的厂商,提供高可用、弹性扩展和智能运维等云原生特性,满足多样化业务需求。
778 26
|
DataWorks 网络协议 Java
DataWorks操作报错合集之离线同步时,报错信息"Out of range value for column 'A' at row 1" ,表示什么意思
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
|
存储 缓存 编译器
Linux源码阅读笔记06-RCU机制和内存优化屏障
Linux源码阅读笔记06-RCU机制和内存优化屏障
|
SQL
SQL中GROUP BY语句与HAVING语句的使用
SQL中GROUP BY语句与HAVING语句的使用
709 1
|
JSON 数据格式
Content type ‘text/plain;charset=UTF-8‘ not supported,这里要把测试文件转为json格式
Content type ‘text/plain;charset=UTF-8‘ not supported,这里要把测试文件转为json格式
|
C++
VS #define _CRT_SECURE_NO_WARNINGS 1 添加了仍然报错
一些小的错误,往往让初学者抓耳挠腮 VS #define _CRT_SECURE_NO_WARNINGS 1 一定要放在最开始的位置
928 2