gpt4 book ai didi

c#带代理的HttpClient

转载 作者:行者123 更新时间:2023-12-03 23:17:06 26 4
gpt4 key购买 nike

我用 HttpClient 对一些资源执行了很多请求.
为了避免舔,我将它用作单个实例。类似的东西...
我想使用代理,那么如何为每个请求使用不同的代理?

谢谢!

public class Program
{
private static HttpClient Client = new HttpClient();
public static void Main(string[] args)
{
Console.WriteLine("Starting connections");
for(int i = 0; i<10; i++)
{
var result = Client.GetAsync("http://aspnetmonsters.com").Result;
Console.WriteLine(result.StatusCode);
}
Console.WriteLine("Connections done");
Console.ReadLine();
}

}

最佳答案

您将需要实现 IWebProxy。

这是一个非常排的示例。

首先实现 IWebProxy

public class MyProxy : IWebProxy {
public MyProxy() { credentials = new NetworkCredential( user, password ); }
private NetworkCredential credentials;
public ICredentials Credentials
{
get = > credentials;
set = > throw new NotImplementedException();
}
private Uri proxyUri;
public Uri GetProxy( Uri destination )
{
return proxyUri; // your proxy Uri
}
public bool IsBypassed( Uri host )
{
return false;
}
private const string user = "yourusername";
private const string password = "password";}

然后将其提供给 HttpClient 中的处理程序
public class MyHttpClient {
internal static HttpResult httpMethod( ... )
{
var _client = client();
try
{
var message = new HttpRequestMessage( method, url );
message.Content = new StringContent( content, Encoding.UTF8, "application/json" );
var result = _client.SendAsync( message ).Result;// handle result
}
catch( Exception e ){}
}
private static HttpClient client()
{
var httpClientHandler = new HttpClientHandler() { Proxy = new MyProxy() };
var httpClient = new MyClient( new Uri( "baseurl" ), httpClientHandler );
return httpClient;

关于c#带代理的HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48795700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com