[C#] Init(flurl)

https://nuget.cdn.azure.cn/v3/index.json


    internal class CustomHttpClientFactory : DefaultHttpClientFactory
    {
        public override HttpMessageHandler CreateMessageHandler()
        {
            var handler = (HttpClientHandler) base.CreateMessageHandler();
            handler.UseCookies = true;
            handler.CookieContainer = new CookieContainer();
            handler.UseProxy = true;
            handler.Proxy = new WebProxy("http://127.0.0.1:8080");
            handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
            return handler;
        }

        public override HttpClient CreateHttpClient(HttpMessageHandler handler)
        {
            var httpClient = base.CreateHttpClient(handler);
            httpClient.DefaultRequestHeaders.ExpectContinue = false;
            return httpClient;
        }
    }
        static void Main(string[] args)
        {
            Bogus.DataSets.Internet internet = new Bogus.DataSets.Internet();
            FlurlHttp.Configure(settings => {
                var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                    ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace
                };
                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
                settings.HttpClientFactory = new CustomHttpClientFactory();
                settings.Timeout=TimeSpan.FromSeconds(5);
                settings.Redirects.Enabled = true; // default true
                settings.Redirects.AllowSecureToInsecure = true; // default false
                settings.Redirects.ForwardAuthorizationHeader = true; // default false
                settings.Redirects.MaxAutoRedirects = 5; // default 10 
            });
        }

/// <summary>
/// Static class that manages cached IFlurlClient instances
/// </summary>
public static class FlurlClientManager
{
    /// <summary>
    /// Cache for the clients
    /// </summary>
    private static readonly ConcurrentDictionary<string, IFlurlClient> Clients =
        new ConcurrentDictionary<string, IFlurlClient>();

    /// <summary>
    /// Gets a cached client for the host associated to the input URL
    /// </summary>
    /// <param name="url"><see cref="Url"/> or <see cref="string"/></param>
    /// <returns>A cached <see cref="FlurlClient"/> instance for the host</returns>
    public static IFlurlClient GetClient(Url url)
    {
        if (url == null)
        {
            throw new ArgumentNullException(nameof(url));
        }

        return PerHostClientFromCache(url);
    }

    /// <summary>
    /// Gets a cached client with a proxy attached to it
    /// </summary>
    /// <returns>A cached <see cref="FlurlClient"/> instance with a proxy</returns>
    public static IFlurlClient GetProxiedClient()
    {
        string proxyUrl = ChooseProxy();

        return ProxiedClientFromCache(proxyUrl);
    }

    private static string ChooseProxy()
    {
        // Do something and return a proxy URL
        return "http://myproxy";
    }

    private static IFlurlClient PerHostClientFromCache(Url url)
    {
        return Clients.AddOrUpdate(
            key: url.ToUri().Host,
            addValueFactory: u => {
                return CreateClient();
            },
            updateValueFactory: (u, client) => {
                return client.IsDisposed ? CreateClient() : client;
            }
        );
    }

    private static IFlurlClient ProxiedClientFromCache(string proxyUrl)
    {
        return Clients.AddOrUpdate(
            key: proxyUrl,
            addValueFactory: u => {
                return CreateProxiedClient(proxyUrl);
            },
            updateValueFactory: (u, client) => {
                return client.IsDisposed ? CreateProxiedClient(proxyUrl) : client;
            }
        );
    }

    private static IFlurlClient CreateProxiedClient(string proxyUrl)
    {
        HttpMessageHandler handler = new SocketsHttpHandler()
        {
            Proxy = new WebProxy(proxyUrl),
            UseProxy = true,
            PooledConnectionLifetime = TimeSpan.FromMinutes(10)
        };

        HttpClient client = new HttpClient(handler);

        return new FlurlClient(client);
    }

    private static IFlurlClient CreateClient()
    {
        HttpMessageHandler handler = new SocketsHttpHandler()
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(10)
        };

        HttpClient client = new HttpClient(handler);

        return new FlurlClient(client);
    }
}
posted @ 2021-11-16 12:13  月渊  阅读(183)  评论(0)    收藏  举报