Flutter如何设置代理

在Flutter开发中,如何为应用设置代理?特别是在使用模拟器或真机调试时,需要让应用走指定的代理服务器。希望能了解具体的配置方法,包括代码实现和可能的配置文件修改。另外,这种情况下是否会影响到应用商店上架?

2 回复

Flutter设置代理方法:

  1. android/gradle.properties添加:
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=7890
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=7890
  1. 或设置环境变量:
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890

根据实际代理地址和端口修改。

更多关于Flutter如何设置代理的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中设置代理可以通过以下几种方式实现:

1. 在Flutter项目中设置代理

方式一:在android/app/src/main/AndroidManifest.xml中配置(仅Android)

<application
    android:usesCleartextTraffic="true">
    <!-- 添加网络权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
</application>

方式二:通过代码设置代理

import 'package:http/http.dart' as http;

void fetchWithProxy() async {
  final proxyUrl = 'http://your-proxy-server:port';
  
  final client = http.Client();
  
  // 设置代理(适用于http包)
  final response = await client.get(
    Uri.parse('https://api.example.com/data'),
    headers: {
      'Proxy-Authorization': 'Basic ' + base64Encode(utf8.encode('username:password')),
    },
  );
  
  print(response.body);
}

2. 使用dio库设置代理(推荐)

import 'package:dio/dio.dart';

void setupProxy() {
  final dio = Dio();
  
  // 设置全局代理
  (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = 
      (HttpClient client) {
    client.findProxy = (uri) {
      return "PROXY your-proxy-server:port;";
    };
    
    // 如果需要认证
    client.authenticate = (uri, scheme, realm) {
      const username = 'your-username';
      const password = 'your-password';
      final credentials = '$username:$password';
      final encoded = base64Encode(utf8.encode(credentials));
      return HttpClientBasicCredentials(encoded);
    };
  };
  
  // 使用dio发起请求
  dio.get('https://api.example.com/data');
}

3. 开发环境代理设置

pubspec.yaml中配置(适用于包下载)

environment:
  sdk: ">=2.12.0 <3.0.0"

# 设置pub代理
# 在终端运行:
# export PUB_HOSTED_URL=https://pub.flutter-io.cn
# export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn

4. 系统级代理设置

Windows:

set HTTP_PROXY=http://proxy-server:port
set HTTPS_PROXY=http://proxy-server:port

macOS/Linux:

export HTTP_PROXY=http://proxy-server:port
export HTTPS_PROXY=http://proxy-server:port

注意事项:

  • 代理设置主要影响网络请求,不影响UI渲染
  • 生产环境建议使用后端服务转发,避免客户端直接配置代理
  • 确保代理服务器支持HTTPS请求
  • 在真机调试时,确保设备和代理服务器在同一网络

推荐使用dio库的方式,因为它提供了更灵活的代理配置选项和更好的错误处理机制。

回到顶部