【问题标题】:How to get any web interaction go through a proxy in a C# code?如何让任何 Web 交互通过 C# 代码中的代理?
【发布时间】:2022-06-13 20:55:25
【问题描述】:

我想让我的代码中的任何类型的网络交互都通过代理,但我找不到如何做到这一点。一直在搜索 Microsoft 文档,但无法弄清楚如何使其工作......

这是我提出请求的代码示例:

int count = 0;
List<string> Links = new List<string>();
using (WebClient wc = new WebClient())
{

  string s = wc.DownloadString("https://www.google.com/search?q=site:drive.google.com+" + resp + "|");
  Regex r = new Regex(@"https:\/\/drive.google.com\/\w+\/\w+");
  foreach (Match m in r.Matches(s))
  {
    count++;
    Links.Add(m.ToString());
  }

任何帮助将不胜感激!

【问题讨论】:

    标签: c# proxy request


    【解决方案1】:

    首先,我强烈建议您使用 HttpClient 而不是 WebClient,Microsoft 也建议使用它 (https://docs.microsoft.com/en-us/dotnet/core/compatibility/networking/6.0/webrequest-deprecated),因为它已过时。 使用 HttpClient 你可以如下:

    首先使用代理的地址/端口创建WebProxy 的实例

    var address = "your address";
    int port = //your port
    
    var webProxy = new WebProxy(address, port)
    {
        BypassProxyOnLocal = true,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential("your-username", "your-pass")
    };
    

    然后创建一个SocketsHttpHandlerlike

    SocketsHttpHandler handler = new()
    {
        Proxy = webProxy,
        UseProxy = true
    };
    

    最后将此处理程序作为 ctor 参数传递给 HttpClient 之类的

    HttpClient client = new HttpClient(handler);
    
    // An example of http client's usage would be this one
    using var response = await client.GetAsync("request-uri");
    var responseText = await response.Content.ReadAsStringAsync();
    

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 2019-06-07
      • 2010-11-06
      相关资源
      最近更新 更多