【问题标题】:How to add HttpClientHandler to url?如何将 HttpClientHandler 添加到 url?
【发布时间】:2017-09-24 15:12:15
【问题描述】:

我有这个请求处理程序:

var httpClientHandler = new HttpClientHandler
{
    Proxy = new WebProxy(proxy.Address, proxy.Port),
    UseProxy = true
};

还有:

var url = new Url(hostUrl)
    .AppendPathSegment(pathSegment);

如何将请求处理程序添加到 FlurlClient?

【问题讨论】:

    标签: c# dotnet-httpclient flurl


    【解决方案1】:

    创建您自己的 ProxiedHttpClientFactory 覆盖 CreateMessageHandler() 方法:

    public class ProxiedHttpClientFactory : DefaultHttpClientFactory
    {
        private readonly string _proxyAddress;
        private readonly int _proxyPort;
    
        public ProxiedHttpClientFactory(string proxyAddress, int proxyPort)
        {
            this._proxyAddress = proxyAddress;
            this._proxyPort = proxyPort;
        }
    
        public override HttpMessageHandler CreateMessageHandler()
        {
            return new HttpClientHandler
            {
                Proxy = new WebProxy(this._proxyAddress, this._proxyPort),
                UseProxy = true
            };
        }
    }
    

    然后使用它:

    var settings = new FlurlHttpSettings
    {
        HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080)
    };
    
    var client = new FlurlClient(settings);
    

    在现有的Url 实例上:

    var url = new Url(hostUrl)
                   .AppendPathSegment(pathSegment)
                   .ConfigureClient(settings => settings.HttpClientFactory = new ProxiedHttpClientFactory("my.proxy.com", 8080));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2015-06-29
      • 2021-01-17
      相关资源
      最近更新 更多