C# HttpClient 或 socks4/5 代理?

C# HttpClient tor socks4/5 proxy?

我可以使用此代码设置 http 代理:

public class CustomFlurlHttpClient : DefaultHttpClientFactory {
    public override HttpClient CreateClient(Url url, HttpMessageHandler m) {
        return base.CreateClient(url, CreateProxyHttpClientHandler("http://192.168.0.103:9090"));
    }

    private HttpClientHandler CreateProxyHttpClientHandler(string proxyUrl, string user = "", string passw = "") {
        NetworkCredential proxyCreds = null;
        var proxyUri = new Uri(proxyUrl);
        proxyCreds = new NetworkCredential (user, passw);
        var proxy = new WebProxy (proxyUri, false) {
            UseDefaultCredentials = false,
            Credentials = proxyCreds
        };
        var clientHandler = new HttpClientHandler {
            UseProxy = true,
            Proxy = proxy,
            PreAuthenticate = true,
            UseDefaultCredentials = false
        };
        if (user != "" && passw != "") {
            clientHandler.Credentials = new NetworkCredential (user, passw);
        }
        return clientHandler;
    }
}
class MainClass {
    public static void Main (string[] args) {
        run ();
        Console.ReadKey ();
    }

    async static void run() {
        using(FlurlClient client = new FlurlClient(c => { c.HttpClientFactory = new CustomFlurlHttpClient();})) {
            var result = await client.WithUrl("https://www.google.com").GetStringAsync();
            Console.WriteLine(result);
        };
    }
}

但不是袜子代理。任何想法如何去做?或支持 async/await 语法的任何其他(未弃用)休息客户端?

可能的解决方案是使用 Extreme.Net 包,它提供 socks 代理处理程序。例如,在上面的代码中,我们需要将 CreateClient 方法替换为:

        public override HttpClient CreateClient(Url url, HttpMessageHandler m)
    {
        var socksProxy = new Socks5ProxyClient("127.0.0.1", 9150);
        var handler = new ProxyHandler(socksProxy);
        return base.CreateClient(url, handler);
    }

而且有效!

一个更好的选择是在自定义工厂中覆盖 CreateMessageHandler 而不是 CreateClient

public class CustomFlurlHttpClient : DefaultHttpClientFactory
{
    public override HttpMessageHandler CreateMessageHandler() {
        var socksProxy = new Socks5ProxyClient("127.0.0.1", 9150);
        return new ProxyHandler(socksProxy);
    }
}

在 .NET 6 中,您可以轻松做到 I answered here

但这里有一个快速的答案:

var proxy = new WebProxy
{
    Address = new Uri("socks5://localhost:8080")
};
//proxy.Credentials = new NetworkCredential(); //Used to set Proxy logins. 
var handler = new HttpClientHandler
{
    Proxy = proxy
};
var httpClient = new HttpClient(handler);

或配置要使用 IHttpClientFactory 创建的命名 HttpClient:

Services.AddHttpClient("WithProxy")
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        var proxy = new WebProxy
        {
            Address = new Uri("socks5://localhost:8080")
        };
        return new HttpClientHandler
        {
                    Proxy = proxy
         };
    });

并且当您注入 IHttpClientFactory 对象时:

httpClient = httpClientFactory.CreateClient("WithProxy");