为什么"(502)Bad Gateway"错误发生了?

时间:2016-04-04 08:59:55

标签: c# .net

Windows 7 SP1 域网络。
.NET Framework 4.6.1。

我的所有Internet浏览器都配置了Internet连接的代理设置(它可以正常工作)。

我需要从Internet下载文件。我配置WebClient因为它将从默认的Internet浏览器中读取代理设置并使用当前进程的凭据,我预计这些条件足以成功下载。但是我得到了异常(查看我的代码中的注释):

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();
}

我做错了什么?

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要检索特定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因您尝试访问的网址而异。