Andrey Bushman
Andrey Bushman

Reputation: 12486

Why "(502) Bad Gateway" error happen?

Windows 7 SP1.
Domain network.
.NET Framework 4.6.1.

All my Internet browsers have configured proxy settings for Internet connections (it works fine).

I need to download file from Internet. I configure WebClient for it will read proxy settings from default Internet browser and use credential of current process and I expected these conditions are enough for successfull downloading. But I get the exception (look the comment in my code):

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

What I did wrong?

enter image description here

Upvotes: 1

Views: 17244

Answers (1)

Gabriel Sadaka
Gabriel Sadaka

Reputation: 1746

You need to retrieve the proxy for the specific URL then set it as the proxy URL of the web request.

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

This is implemented just in case the proxy uri is different depending on the url you are trying to access.

Upvotes: 1

Related Questions