c#HttpClient与代理

时间:2018-02-14 20:31:39

标签: c# proxy httpclient

我使用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();
    }

}

3 个答案:

答案 0 :(得分:2)

其实很简单。
您需要做的就是在 HttpClient 构造函数中设置处理程序。
然后在处理程序中设置代理。
像这样:

public class Program
{

    public static async System.Threading.Tasks.Task Main(string[] args)
    {
        string url = "http://aspnetmonsters.com";

        using (System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler()
        {
            Proxy = new System.Net.WebProxy("http://127.0.0.1:8888"),
            UseProxy = true,
        })
        {

            using (System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient(handler))
            {
                System.Console.WriteLine("Starting connections");

                for (int i = 0; i < 10; i++)
                {
                    await hc.GetAsync(url);

                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
                    hc.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148");
                    hc.DefaultRequestHeaders.Add("Accept-Language", "fr-FR, fr;q=0.9, en;q=0.8, it;q=0.7, *;q=0.5");
                    hc.DefaultRequestHeaders.Add("Referer", "https://www.baidu.com");

                    using (System.Net.Http.HttpResponseMessage response = await hc.GetAsync(url))
                    {
                        // using (var fs = new System.IO.MemoryStream())
                        // { await response.Content.CopyToAsync(fs); }
                        byte[] ba = await response.Content.ReadAsByteArrayAsync();

                    } // End Using response 

                } // Next i 

                System.Console.WriteLine("Ending connections");
            } // End Using hc 

        } // End Using handler 

        System.Console.WriteLine("--- Press any key to continue --- ");
        System.Console.ReadKey();
    } // End Task Main 

} // End Class Program 

答案 1 :(得分:0)

基本上,为了能够更改代理,您需要HttpClientHandler上的参考 这里有一个简单的例子:C# use proxy with HttpClient request
另一个在这里:Simple C# .NET 4.5 HTTPClient Request Using Basic Auth and Proxy

我建议将HttpClientHandler保留在私有字段上,并在每次需要时使用引用来更改代理。
请记住,如果您需要同时使用不同的代理,则需要拥有HttpClientHandler类的多个实例。

如果您需要我为此制作示例代码。平我。

谢谢。

答案 2 :(得分:0)

您将需要实现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;