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

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/contentcnn/93248.html

六、扩展建议

  1. 拦截器模式:实现请求/响应拦截器,统一处理认证、日志、缓存
  2. 连接池管理:优化HttpClient连接复用策略
  3. OAuth2支持:集成令牌自动刷新机制
  4. 性能监控:添加请求耗时统计和性能分析
  5. 测试套件:使用xUnit编写单元测试和集成测试
posted @ 2025-12-18 11:02  风一直那个吹  阅读(5)  评论(0)    收藏  举报