【问题标题】:c# HttpClient with proxyc# HttpClient 带代理
【发布时间】:2018-02-14 20:31:38
【问题描述】:

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

}

【问题讨论】:

  • 为您拥有的每个代理创建和验证 HttClient。然后使用与您的请求地址匹配的实例

标签: c# proxy httpclient


【解决方案1】:

其实很简单。
您需要做的就是在 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 

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

      谢谢。

      【讨论】:

      • 但是如何在 HttpClientHandler 创建后将其设置为 HttpClient 的实例?
      • @Sanja Melnichuk HttpClientHandler 只需要在构造时设置。如果您保留引用,则可以对其进行更改而无需重建 HttpClient
      • 所以我有一个静态 httpclient 和 HttpCleintHandler,我在不同的线程中使用它,每个线程使用它自己的代理,我如何确定我为即将到来的请求更改代理?
      • @Sanja Melnichuk 如果您更仔细地阅读我的原始答案,我会说如果您想同时使用它,您需要拥有多个。只是为了澄清最昂贵的创建是 HttpClientHandler 而不是 HttpClient。
      • 这是不正确的建议。虽然您可以在发送第一个请求之前更改附加到 httpclient 的处理程序的代理,但任何后续更改代理的尝试都将导致抛出异常。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多