LoginSignup
0
0

FlutterでProxyman等を使うときのHTTPクライアントコード

Last updated at Posted at 2024-05-18

はじめに

ProxymanやCharlesを使うときhttpパッケージやdioパッケージの利用箇所に変更が必要です。
Proxymanの手順にもやり方が書いてあるのですが、書き方がだいぶ古いので最近対応したときのコードを残したメモです。

dioパッケージの場合

  final dio = Dio();

  // デバッグ中だけ設定
  if (kDebugMode) {
    dio.httpClientAdapter = IOHttpClientAdapter(
      createHttpClient: () {
        final client = HttpClient();
        client.findProxy = (uri) {
          // dart-defineやdart-define-from-fileから読み取る場合
          const yourLocalIp = String.fromEnvironment('YOUR_LOCAL_IP');
          const proxyPort = String.fromEnvironment('PROXY_PORT');
          final proxy = Platform.isAndroid
              ? '$yourLocalIp:$proxyPort'
              : 'localhost:$proxyPort';

          return 'PROXY $proxy';
        };
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => Platform.isAndroid;
        return client;
      },
    );
  }

dio_proxy_adapterってパッケージもありますが、全然メンテされてないのでオススメできません。

httpパッケージの場合

  final httpClient = HttpClient();

  // デバッグ中だけ設定
  if (kDebugMode) {
    httpClient.findProxy = (uri) {
      // dart-defineやdart-define-from-fileから読み取る場合
      const yourLocalIp = String.fromEnvironment('YOUR_LOCAL_IP');
      const proxyPort = String.fromEnvironment('PROXY_PORT');
      final proxy = Platform.isAndroid
          ? '$yourLocalIp:$proxyPort'
          : 'localhost:$proxyPort';

      return 'PROXY $proxy';
    };
    httpClient.badCertificateCallback =
        (X509Certificate cert, String host, int port) => Platform.isAndroid;
  }

  final client = IOClient(httpClient);

おまけ(dart-define-from-fileの部分)

こんな感じのjsonを用意します。

dev.json
{
    "YOUR_LOCAL_IP": "192.168.0.30",
    "PROXY_PORT": "9090"
}

起動時にこうします。

flutter run --dart-define-from-file=dev.json

VSCodeならこんな感じです。

launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "debug",
            "request": "launch",
            "type": "dart",
            "args": [
                "--dart-define-from-file=dev.json"
              ]
        },
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