LoginSignup
0

More than 3 years have passed since last update.

OkHttpで認証付きのプロキシ通信を行う

Posted at

Androidだと、認証なしのプロキシの場合は端末の設定画面から設定することができますが、認証付きのプロキシは端末の設定画面から設定することができません。(ユーザー名とパスワードを入力できない。)

今回どうしても認証付きのプロキシで通信を行いたかったので
、色々と調べてみたのですが、OkHttpでサクッと対応できてしまったのでメモがてら投稿。

proxyAuthenticator を使う

OkHttpClient.BuilderproxyAuthenticator で認証情報を設定します。

下記サンプルコードでは、ユーザー名 username 、パスワード password としています。


val client = OkHttpClient.Builder()
    .proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("http://example.com", 3128)))
    .proxyAuthenticator(object : Authenticator {
        override fun authenticate(route: Route?, response: Response): Request? {
            val credential = Credentials.basic("username", "password")
            return response.request.newBuilder()
                .header("Proxy-Authorization", credential)
                .build()
        }
    })
    .build()

あとはこの client をRetrofitとかで使うようにすればOKです。

参考

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
0