Windows 7 SP1。
域网络。
.NET框架4.6.1。
我所有的Internet浏览器都为Internet连接配置了代理设置(它工作得很好)。
我需要从互联网上下载文件。我为它配置了WebClient,将从默认的互联网浏览器读取代理设置,并使用当前进程的凭据,我希望这些条件足以成功下载。但是我得到了一个异常(看看我代码中的注释):
static void Main(string[] args) {
String file_name = Path.GetRandomFileName();
String full_path = Environment.ExpandEnvironmentVariables(
Path.Combine(@"%LocalAppData%\Temp", file_name));
using (WebClient client = new WebClient()) {
client.Credentials = CredentialCache.DefaultCredentials;
//client.Proxy = WebRequest.GetSystemWebProxy();
var proxyUri = WebRequest.GetSystemWebProxy()
.GetProxy(new Uri("https://yadi.sk/i/jPScGsw9qiSXU"));
try {
client.DownloadFile(proxyUri, full_path);
}
catch (Exception ex) {
// The remote server returned an error: (502) Bad Gateway.
Console.WriteLine(ex.Message);
}
}
Console.WriteLine("Press any key for exit.");
Console.ReadKey();
}我做错了什么?

发布于 2016-04-04 17:20:23
您需要检索特定URL的代理,然后将其设置为web请求的代理URL。
static void Main(string[] args) {
String file_name = Path.GetRandomFileName();
String full_path = Environment.ExpandEnvironmentVariables(
Path.Combine(@"%LocalAppData%\Temp", file_name));
using (WebClient client = new WebClient()) {
client.Credentials = CredentialCache.DefaultCredentials;
var proxyUri = WebRequest.GetSystemWebProxy()
.GetProxy(new Uri("https://yadi.sk/i/jPScGsw9qiSXU"));
client.Proxy = new WebProxy(proxyUri);
client.Proxy.Credentials = CredentialCache.DefaultCredentials;
try {
client.DownloadFile("https://yadi.sk/i/jPScGsw9qiSXU", full_path);
}
catch (Exception ex) {
// The remote server returned an error: (502) Bad Gateway.
Console.WriteLine(ex.Message);
}
}
Console.WriteLine("Press any key for exit.");
Console.ReadKey();
}这是在代理uri根据您试图访问的url而不同的情况下实现的。
https://stackoverflow.com/questions/36398366
复制相似问题