C# HttpClient tor socks4/5 代理?
Posted
技术标签:
【中文标题】C# HttpClient tor socks4/5 代理?【英文标题】:C# HttpClient tor socks4/5 proxy? 【发布时间】:2017-04-08 11:16:54 【问题描述】:我可以使用此代码设置 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);
;
但不是 socks 代理。任何想法如何做到这一点?或者任何其他(未弃用)支持异步/等待语法的休息客户端?
【问题讨论】:
一般来说,任何你可以用 HttpClient 做的事情,你都可以用 Flurl 做。不幸的是,我没有找到任何示例,而且我个人对 SOCKS 也不是很熟悉。也许将其重新定义为 HttpClient 问题,有人会插话。 【参考方案1】:可能的解决方案是使用提供 socks 代理处理程序的 Extreme.Net
包。例如,在上面的代码中,我们需要将 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);
而且它有效!
【讨论】:
不错!这看起来确实可行,但可以覆盖仅创建 MessageHandler 并让默认工厂创建 HttpClient,正如我将在新答案中演示的那样。 Extreme.Net 已弃用? 根据 nuget – 是的【参考方案2】:更好的选择是在您的自定义工厂中覆盖 CreateMessageHandler
而不是 CreateClient
:
public class CustomFlurlHttpClient : DefaultHttpClientFactory
public override HttpMessageHandler CreateMessageHandler()
var socksProxy = new Socks5ProxyClient("127.0.0.1", 9150);
return new ProxyHandler(socksProxy);
【讨论】:
以上是关于C# HttpClient tor socks4/5 代理?的主要内容,如果未能解决你的问题,请参考以下文章