LoginSignup
16
20

More than 5 years have passed since last update.

c# HttpClient で認証付きのプロキシーを利用する

Posted at

HttpClient のコンストラクタに、プロキシーの情報をセットしたHttpClientHandler
のインスタンスを渡す。

class Program
{
    private static readonly string proxyUrl = "http://proxy.foo.com:8080";
    private static readonly string proxyAccount = "account";
    private static readonly string proxyPassword = "password";
    private static readonly string targetUrl = "http://www.bar.com";

    static void Main(string[] args)
    {
        // HttpClientHandlerにProxy情報を設定する
        HttpClientHandler ch = new HttpClientHandler();
        ch.Proxy = new WebProxy(proxyUrl);
        ch.Proxy.Credentials = new NetworkCredential(proxyAccount, proxyPassword);
        ch.UseProxy = true;

        // HttpClientHandlerを用いてHttpClientを生成
        HttpClient client = new HttpClient(ch);
        try
        {
            // GETでレスポンスを取得
            var task = client.GetStringAsync(targetUrl);
            task.Wait();
            Console.WriteLine(task.Result);
        }
        catch (Exception e)
        {
            Exception e2 = e.GetBaseException();
            System.Console.WriteLine(e2.Message);
        }
    }
}
16
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
20