abr*_*tov 7 c# proxy socks dotnet-httpclient flurl
我可以使用以下代码设置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);
};
}
}
Run Code Online (Sandbox Code Playgroud)
但不是袜子代理。有什么想法如何去做吗?或者任何其他(未弃用)支持异步/等待语法的其余客户端?
在 .NET 6 中,您可以轻松做到这一点,正如我在这里回答的那样
但这里有一个快速答案:
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);
Run Code Online (Sandbox Code Playgroud)
HttpClient或配置要创建的命名IHttpClientFactory:
Services.AddHttpClient("WithProxy")
.ConfigurePrimaryHttpMessageHandler(() =>
{
var proxy = new WebProxy
{
Address = new Uri("socks5://localhost:8080")
};
return new HttpClientHandler
{
Proxy = proxy
};
});
Run Code Online (Sandbox Code Playgroud)
当你注入IHttpClientFactory对象时:
httpClient = httpClientFactory.CreateClient("WithProxy");
Run Code Online (Sandbox Code Playgroud)
可能的解决方案是使用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);
}
Run Code Online (Sandbox Code Playgroud)
它有效!