LoginSignup
0
0

【Android】WebViewでプロキシ(proxy)の設定をする方法

Posted at

Androidアプリ開発において、WebViewで開くページにプロキシを適用させる必要があったので、その方法についてメモしておきます。

ProxyController を使えばOK

Webkit にある ProxyController を使えばOKでした。

使ってみる

ProxyController を使ってみます。

Webkit の依存を追加

dependencies {
    implementation "androidx.webkit:webkit:1.8.0"
}

サンプル実装

// プロキシを設定
if (WebViewFeature.isFeatureSupported(PROXY_OVERRIDE)) {
    val proxyConfig = ProxyConfig.Builder()
        .addProxyRule("proxy.example.com") // プロキシ
        .addBypassRule("exclude.example.com") // プロキシから除外する設定
        .build()
    val executor = Executor {}
    val listener = Runnable {}
    ProxyController.getInstance().setProxyOverride(proxyConfig, executor, listener)
}

// プロキシを解除
if (WebViewFeature.isFeatureSupported(PROXY_OVERRIDE)) {
    val executor = Executor {}
    val listener = Runnable {}
    ProxyController.getInstance().clearProxyOverride(executor, listener)
}

要点メモ

  • ProxyController.getInstance() の呼び出しには WebViewFeature.isFeatureSupported(PROXY_OVERRIDE) が必要
  • ProxyConfig でプロキシの設定を指定
    • addProxyRule でプロキシのURLを指定
      • ポートも指定する場合は addProxyRule("proxy.example.com:1111") みたいに指定
    • addBypassRule でプロキシから除外したいURLを指定
      • setReverseBypassEnabledtrue にすることで、addBypassRule で指定したURLのみプロキシを使うようにもできる
  • executor: Executor listener: Runnable はそれぞれ下記の通り
    • executor: Executor → リスナーの実行を管理するオブジェクト
    • listener: Runnable → プロキシ設定の変更が適用されたときに呼び出されるリスナー
    • プロキシの設定は即座に反映されるわけではないので、それのタイミングをハンドリングしたい場合に使う。(細かい調整をしない限りは空でもよさそう :thinking:
  • プロキシの設定はアプリ内のWebView全体に影響するので、プロキシ設定が不要になったら解除する
0
0
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
0
0