使用带有代理的c# WebClient -不向代理服务器发出请求

本文关键字:代理服务器 请求 WebClient 代理 | 更新日期: 2023-09-27 18:11:52

我们有一个后台操作(窗口服务),我们想通过代理服务器使用。

基本上,我们是这样做的:

public WebClient GetWebClient(){
   var webClient = new WebClient();
   webClient.proxy = new WebProxy(Configuration.ProxyHost, Configuration.ProxyPort);
   // add a bunch of headers to the WebClient (sessionids, etc.)
   return webClient;
}

代理是一个我们已经配置自己使用FreeProxy。

我已经在我正在测试的机器上启用了日志记录,并且可以确认在Firefox中使用它时正在向代理发出请求。

代理服务器不需要身份验证,除了IP必须在我们的办公室内(从Firefox的证据来看,我认为这不是问题)。

然而,在我们的后台进程中,当我使用web客户端时,我似乎没有使用代理:

using(var wc = GetWebClient())
using(var s = wc.OpenRead("someurl"))
using(var sr = new StreamReader(s)){
    return sr.ReadToEnd();
}

我没有收到来自代理的错误,然而,似乎我们只是在没有它的情况下进行,即使代理已经明确设置。

信息似乎返回正常,只是没有通过我们的代理。

使用具有WebClient的代理时是否缺少某些东西?

编辑:更多细节。如果我们在服务器上禁用代理服务,那么我们会得到一个异常,我们无法连接。因此,看起来web客户端试图接触代理,但流量实际上并没有通过代理。

Inner Exception: SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

使用带有代理的c# WebClient -不向代理服务器发出请求

原来FreeProxy不接受HTTPS流量。

我猜代理必须返回它可以路由的流量类型,如果它不能,web客户端什么也不做。

切换到使用Burp套件作为我们的代理,因为它可以接受HTTPS。http://portswigger.net/burp/

您必须在默认情况下配置windows以使用代理,或者在代码中手动设置代理,参见:http://msdn.microsoft.com/en-us/library/system.net.webclient.proxy(v=VS.100).aspx

据我所知,您正在正确使用WebClient类。我可以看到下面的请求…

using(var client = new WebClient())
{
    client.Proxy = new WebProxy("localhost", 8888);
    Console.WriteLine(client.DownloadString("http://www.google.com"));
}

在我的本地机器上运行的Fiddler。现在如果我关闭Fiddler,我得到webeexception:

Unable to connect to the remote server

内部SocketException:

No connection could be made because the target machine actively refused it 127.0.0.1:8888

所以,话虽如此,我的猜测是,你的代理是按预期工作,但它只是没有记录传出的HTTP请求。