【问题标题】:How do I connect to the https web with an http proxy?如何使用 http 代理连接到 https 网络?
【发布时间】:2021-03-10 06:10:17
【问题描述】:

我正在使用翻译,因为我是韩国人。即使我不擅长,我也会感谢您的理解。

我想使用 http 代理从 c# 发送一个 post 请求到 https web 到 http 代理。

            HttpClient httpclient = null;
            proxy = "http://" + proxy;
            HttpClientHandler handler = new HttpClientHandler()
            {

                Proxy = new WebProxy(proxy),
                UseProxy = true,
            };

            httpclient = new HttpClient(handler);

这是我的 C# 代码

但我无法连接到 https 网络。

有没有办法在c#中使用http客户端模块产生和下面python代码一样的效果?

        proxy={ 'https' : 'http://' + input_proxy }
        resp=self.desktop.post(self.url,self.payload,proxies=proxy)

【问题讨论】:

标签: c# http https proxy dotnet-httpclient


【解决方案1】:

我推荐你访问这个链接:HttpClient and using a proxy

首先,创建一个代理对象

var proxy = new WebProxy
{
    Address = new Uri($"http://{proxyHost}:{proxyPort}"),
    BypassProxyOnLocal = false,
    UseDefaultCredentials = false,

    // *** These creds are given to the proxy server, not the web server ***
    Credentials = new NetworkCredential(
        userName: proxyUserName,
        password: proxyPassword)
};

现在创建一个使用该代理的客户端处理程序

var httpClientHandler = new HttpClientHandler
{
    Proxy = proxy,
};

如果您不需要通过网络服务器进行身份验证,请忽略此部分:

if (needServerAuthentication)
{
    httpClientHandler.PreAuthenticate = true;
    httpClientHandler.UseDefaultCredentials = false;

    // *** These creds are given to the web server, not the proxy server ***
    httpClientHandler.Credentials = new NetworkCredential(
        userName: serverUserName,
        password: serverPassword);
}

最后,创建 HTTP 客户端对象

var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);

【讨论】:

  • 可以访问https吗?
  • 是的,但我认为如果服务器只支持更高的 TLS 版本,如 TLS 1.2,除非您的客户端 PC 默认配置为使用更高的 TLS 版本,否则它仍然会失败。为了克服这个问题,在设置地址之前添加这个代码:System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;Address = new Uri($"https://{proxyHost}:{proxyPort}"), ...
【解决方案2】:

如果您想代理使用,也可以使用著名的 c# 库进行 RESTAPI 通信 RESTSharp

    var client = new RestClient("http://example.com")
    client.Proxy = new WebProxy("http://proxy.example.com")

【讨论】:

  • 这比使用HttpClient 更好吗?不是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多