如何在 Flurl 中为 Web 请求使用代理?

How can I use proxies for web requests in Flurl?

我有一个使用 Flurl 客户端的简单 post 请求,我想知道如何使用 IP、端口、用户名和密码等信息使用代理发出此请求。

string result = await atc.Request(url)
    .WithHeader("Accept", "application/json")
    .WithHeader("Content-Type", "application/x-www-form-urlencoded")
    .WithHeader("Host", "www.website.com")
    .WithHeader("Origin", "http://www.website.com")
    .PostUrlEncodedAsync(new { st = colorID, s = sizeID, qty = 1 })
    .ReceiveString();

我在寻找类似的答案并找到了这个: https://github.com/tmenier/Flurl/issues/228

这是一份 link 内容的副本。它对我有用!

You can do this with a custom factory:

using Flurl.Http.Configuration;

public class ProxyHttpClientFactory : DefaultHttpClientFactory {
    private string _address;

    public ProxyHttpClientFactory(string address) {
        _address = address;
    }

    public override HttpMessageHandler CreateMessageHandler() {
        return new HttpClientHandler {
            Proxy = new WebProxy(_address),
            UseProxy = true
        };
    }
} 

To register it globally on startup:

FlurlHttp.Configure(settings => {
    settings.HttpClientFactory = new ProxyHttpClientFactory("http://myproxyserver");
});