如何通过Flutter获取Android/iOS设备的代理设置?
Hey there! Great question—since Flutter doesn’t provide an out-of-the-box API to fetch device proxy settings, you’ll need to leverage platform-specific native code and bridge it to your Flutter app using MethodChannels. Let’s walk through how to do this for both Android and iOS.
On Android, you can retrieve proxy settings in two common ways: via the ConnectivityManager API or by reading system properties. Here’s how to implement both:
方法1:使用ConnectivityManager
This method gives you access to the active network’s proxy configuration. Add this code to your Android native project (e.g., in MainActivity.kt):
import android.content.Context import android.net.ConnectivityManager import android.net.ProxyInfo import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val CHANNEL = "com.yourapp/proxy" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if (call.method == "getProxySettings") { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val network = connectivityManager.activeNetwork val proxyInfo = connectivityManager.getLinkProperties(network)?.proxyInfo val proxyMap = mutableMapOf<String, String?>() proxyInfo?.let { proxyMap["host"] = it.host proxyMap["port"] = it.port.toString() proxyMap["exclusionList"] = it.exclusionList.joinToString(",") } result.success(proxyMap) } else { result.notImplemented() } } } }
方法2:读取系统属性
If you need to get global proxy settings (not just for the active network), you can read system properties directly:
val proxyHost = System.getProperty("http.proxyHost") val proxyPort = System.getProperty("http.proxyPort") val proxyExclusions = System.getProperty("http.nonProxyHosts")
Note: You’ll need the ACCESS_NETWORK_STATE permission in your AndroidManifest.xml for these methods to work.
On iOS, you’ll use the CFNetwork framework to fetch system proxy settings. Here’s the Swift implementation for your iOS native project (e.g., in AppDelegate.swift):
import UIKit import Flutter import CFNetwork @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { private let CHANNEL = "com.yourapp/proxy" override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let controller : FlutterViewController = window?.rootViewController as! FlutterViewController let channel = FlutterMethodChannel(name: CHANNEL, binaryMessenger: controller.binaryMessenger) channel.setMethodCallHandler { [weak self] call, result in guard call.method == "getProxySettings" else { result.notImplemented() return } let proxySettings = CFNetworkCopySystemProxySettings().takeRetainedValue() as NSDictionary let httpProxy = proxySettings[kCFNetworkProxiesHTTPProxy] as? String let httpPort = proxySettings[kCFNetworkProxiesHTTPPort] as? Int let exclusionList = proxySettings[kCFNetworkProxiesExceptionsList] as? [String] var proxyMap = [String: Any?]() proxyMap["host"] = httpProxy proxyMap["port"] = httpPort?.description proxyMap["exclusionList"] = exclusionList?.joined(separator: ",") result.success(proxyMap) } GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
Note: iOS doesn’t require any special permissions for this, and this works for both HTTP and HTTPS proxies.
Now, in your Flutter Dart code, set up the MethodChannel to call the native methods:
import 'package:flutter/services.dart'; class ProxyService { static const MethodChannel _channel = MethodChannel('com.yourapp/proxy'); static Future<Map<String, String?>?> getProxySettings() async { try { final Map<dynamic, dynamic>? result = await _channel.invokeMethod('getProxySettings'); if (result == null) return null; return result.map((key, value) => MapEntry(key as String, value as String?)); } on PlatformException catch (e) { print("Failed to get proxy settings: ${e.message}"); return null; } } } // Usage example in a widget: void fetchProxy() async { var proxy = await ProxyService.getProxySettings(); if (proxy != null) { print("Proxy Host: ${proxy['host']}"); print("Proxy Port: ${proxy['port']}"); print("Excluded Hosts: ${proxy['exclusionList']}"); } else { print("No proxy configured"); } }
额外注意事项
- Make sure to replace
com.yourapp/proxywith your own unique channel name to avoid conflicts. - For Android, if your app targets API level 33+, you might need to handle runtime permissions for
ACCESS_NETWORK_STATE. - On iOS,
CFNetworkCopySystemProxySettingsreturns all system proxy configurations, so you might want to filter for the relevant one (e.g., HTTP vs SOCKS) based on your needs.
内容的提问来源于stack exchange,提问作者Alloysius Goh

