0

I have code to launch an http request from this code on githb.

How do I add a proxy to my http request?

public HttpRequestMessage MakeRequest(HttpMethod method, string url, IEnumerable<KeyValuePair<string, string>> args = null, string proxy)
{
    HttpRequestMessage content = new HttpRequestMessage(method, GetRequestUrl(url));
    if (args is null)
        args = Enumerable.Empty<KeyValuePair<string, string>>();
   
    content.Headers.Add("X-MBX-APIKEY", Client.APIKey);
    if (method == HttpMethod.Get)
    {
        content.RequestUri = new Uri(content.RequestUri.OriginalString +
            CreateQueryString(BuildRequest(args)));
    } else content.Content = new FormUrlEncodedContent(BuildRequest(args));

    return content;
}
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
David Peterson
  • 552
  • 14
  • 31

2 Answers2

0

You can create your own Proxy class.

public class YourProxy : IWebProxy
{
    private Uri uri;

    public YourProxy(Uri uri)
    {
        this.uri = uri;
    }

    public ICredentials Credentials { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

    public Uri GetProxy(Uri destination)
    {
        throw new NotImplementedException();
    }

    public bool IsBypassed(Uri host)
    {
        throw new NotImplementedException();
    }
}

Below way you can add the proxy to the request.

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.CreateHttp(uri);
IWebProxy proxy = new YourProxy(new Uri("http://xx.xx.xx.xxx:xxxx"));
proxy.Credentials = new NetworkCredential("xxxx", "xxxx");
webrequest.Proxy = proxy;

Reference: https://stackoverflow.com/a/17558603/6527049

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

You can create your own HttpClientFactory and use it to send requests. It will provide proxy support for your request.

public class ProxyHttpClientFactory: HttpClientFactory {
  private readonly ICredentials _credentials;
  private readonly IWebProxy _proxy;

  public ProxyHttpClientFactory(ProxyOptions options) {
    _credentials = new NetworkCredential(options.Login, options.Password, options.ProxyUri);
    _proxy = new WebProxy(options.ProxyUri, true, null, _credentials);
  }

  protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args) {
    Console.WriteLine("Proxy got called");

    return new HttpClientHandler {
      UseProxy = true,
      Proxy = _proxy,
      Credentials = _credentials,
      SslProtocols = SslProtocols.Tls12,
      UseCookies = false,
      ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>true
    };
  }
}
V. Parshin
  • 48
  • 6