惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
C
Cisco Blogs
The Hacker News
The Hacker News
T
Threatpost
S
Schneier on Security
K
Kaspersky official blog
Spread Privacy
Spread Privacy
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
NISL@THU
NISL@THU
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
Security Latest
Security Latest
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
博客园 - 叶小钗
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
News and Events Feed by Topic
爱范儿
爱范儿
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Project Zero
Project Zero
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cisco Talos Blog
Cisco Talos Blog
GbyAI
GbyAI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
T
Tenable Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
Forbes - Security
Forbes - Security
博客园 - 三生石上(FineUI控件)
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News and Events Feed by Topic
V
V2EX
Webroot Blog
Webroot Blog
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale
M
MIT News - Artificial intelligence
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
L
LangChain Blog
W
WeLiveSecurity
Cloudbric
Cloudbric

博客园 - Hey,Coder!

Elasticsearch ILM 与 Data Stream 概念及实例说明文档 portainer Ocelot + Consul + SignalR 粘性会话 正交软件架构 docker postgresql17 主从复制 rabbitmq总结与c#示例 docker rabbitmq quartz dashboard docker consul registrator 服务自动注册consul 微服务动态扩容 ubuntu24.04 安装docker RAG 检索增强生成 软考 - 架构设计师 知识点总结 c# MailKit3.4.3 发送邮件、附件 nginx 反向代理postgresql c# 信号量 elsa 3.5 中间件记录最后执行的节点数据 xp密钥 c# System.Text.Json 反序列化Dictionary<string,object>时未转换基础类型的处理方法 docker配置代理 openclaw 接入 LMStudio的模型服务 wpf canvas 移动 缩放 windows平台openclaw搭建 wpf scrollerview触摸滚动 c# 动态切换sqlsugar连接字符串 c# Elastic.Clients.Elasticsearch 动态查询 c# es 封装Elastic.Clients.Elasticsearch c# scrollerview滚动到指定元素位置 WPF 重写Expander 基于elsa工作流封装一套变量、组件的体系 常用活动重写 DynamicExpresso 轻量级动态表达式库 c# elsa 3.5.2 程序化工作流常用功能及自定义中间件 leaflet docker 连接老版本的sqlserver ssl错误 c# quartz 动态创建任务 控制任务运行和停止 依赖注入 cefsharp 模拟点击 批量重置数据库的数据 docker 复制远程镜像本地并创建容器 c# newtonsoft dynamic
httphelper封装
Hey,Coder! · 2026-06-24 · via 博客园 - Hey,Coder!

restsharp在docker偶发接口调用慢的问题,改用原生Httpclient重写

public class HttpHelperEx : IHttpHelper, IDisposable
{
    private readonly HttpClient _httpClient;

    private readonly JsonSerializerOptions _jsonOptions;

    public HttpHelperEx(double timeout = 30.0)
    {
        SocketsHttpHandler handler = new SocketsHttpHandler
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(2.0),
            PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1.0),
            MaxConnectionsPerServer = 50,
            UseProxy = false,
            ConnectTimeout = TimeSpan.FromSeconds(5.0)
        };
        _httpClient = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromSeconds(timeout)
        };
        _jsonOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
    }

    public TResponse? Post<TResponse>(string url, object request, Dictionary<string, string>? headers = null)
    {
        Dictionary<string, string> headers2 = headers;
        return Task.Run(async delegate
        {
            using HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = JsonContent.Create(request, null, _jsonOptions)
            };
            AddHeaders(httpRequest, headers2);
            using HttpResponseMessage response = await _httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();
            if (response.Content.Headers.ContentLength == 0)
            {
                return default(TResponse);
            }

            return await response.Content.ReadFromJsonAsync<TResponse>(_jsonOptions);
        }).GetAwaiter().GetResult();
    }

    public TResponse? Get<TResponse>(string url, Dictionary<string, string>? headers = null)
    {
        Dictionary<string, string> headers2 = headers;
        return Task.Run(async delegate
        {
            using HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, url);
            AddHeaders(httpRequest, headers2);
            using HttpResponseMessage response = await _httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();
            if (response.Content.Headers.ContentLength == 0)
            {
                return default(TResponse);
            }

            return await response.Content.ReadFromJsonAsync<TResponse>(_jsonOptions);
        }).GetAwaiter().GetResult();
    }

public class HttpHelperEx : IDisposable
{
    private readonly HttpClient _httpClient;
    private readonly JsonSerializerOptions _jsonOptions;

    public HttpHelperEx(double timeout = 30)
    {
        var handler = new SocketsHttpHandler
        {
            // ✅ Docker Ubuntu 6秒问题的根因解决
            //AddressFamily = AddressFamily.InterNetwork,

            PooledConnectionLifetime = TimeSpan.FromMinutes(2),
            PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1),
            MaxConnectionsPerServer = 50,

            UseProxy = false,
            ConnectTimeout = TimeSpan.FromSeconds(5),
        };

        _httpClient = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromSeconds(timeout)
        };

        _jsonOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
    }

    /// <summary>
    /// 异步 POST 请求
    /// </summary>
    public async Task<TResponse?> PostAsync<TResponse>(
        string url,
        object request,
        Dictionary<string, string>? headers = null,
        CancellationToken cancellationToken = default)
    {
        using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = JsonContent.Create(request, options: _jsonOptions)
        };

        AddHeaders(httpRequest, headers);

        using var response = await _httpClient.SendAsync(
            httpRequest,
            HttpCompletionOption.ResponseHeadersRead,
            cancellationToken);

        response.EnsureSuccessStatusCode();

        if (response.Content.Headers.ContentLength == 0)
            return default;

        return await response.Content.ReadFromJsonAsync<TResponse>(
            _jsonOptions,
            cancellationToken);
    }

    /// <summary>
    /// 异步 GET 请求
    /// </summary>
    public async Task<TResponse> GetAsync<TResponse>(
        string url,
        Dictionary<string, string> headers = null,
        CancellationToken cancellationToken = default)
    {
        using var httpRequest = new HttpRequestMessage(HttpMethod.Get, url);
        AddHeaders(httpRequest, headers);

        using var response = await _httpClient.SendAsync(
            httpRequest,
            HttpCompletionOption.ResponseHeadersRead,
            cancellationToken);

        response.EnsureSuccessStatusCode();

        if (response.Content.Headers.ContentLength == 0)
            return default;

        return await response.Content.ReadFromJsonAsync<TResponse>(
            _jsonOptions,
            cancellationToken);
    }

    /// <summary>
    /// 同步 POST 请求(通过异步方法实现)
    /// </summary>
    public TResponse Post<TResponse>(
        string url,
        object request,
        Dictionary<string, string> headers = null)
    {
        // 调用异步方法,使用 ConfigureAwait(false) 避免死锁风险
        return PostAsync<TResponse>(url, request, headers)
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();
    }

    /// <summary>
    /// 同步 GET 请求(通过异步方法实现)
    /// </summary>
    public TResponse Get<TResponse>(
        string url,
        Dictionary<string, string> headers = null)
    {
        // 调用异步方法,使用 ConfigureAwait(false) 避免死锁风险
        return GetAsync<TResponse>(url, headers)
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();
    }

    private static void AddHeaders(HttpRequestMessage request, Dictionary<string, string>? headers)
    {
        if (headers == null) return;

        foreach (var header in headers)
        {
            request.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }
    }

    public void Dispose()
    {
    }
}