Flutter for OpenHarmony

插件介绍

dio是一款功能强大的Flutter HTTP客户端库,专为网络请求设计,支持RESTful API、FormData、拦截器、请求取消、文件上传/下载等功能。该库已针对开源鸿蒙(OpenHarmony)平台进行了深度适配,能够在鸿蒙设备上高效运行,为跨平台开发提供了完整的网络解决方案。

核心特性

  • 全面的HTTP支持:GET、POST、PUT、DELETE等所有HTTP方法
  • 强大的拦截器:支持请求拦截、响应拦截和错误拦截,可用于统一处理认证、日志、错误等
  • 请求取消:通过CancelToken实现请求的取消功能
  • 文件操作:支持文件上传和下载
  • 超时处理:灵活的超时配置
  • FormData支持:方便地处理表单数据和文件上传
  • Mock请求:内置MockAdapter,便于测试
  • HarmonyOS适配:针对鸿蒙平台的网络栈和文件系统进行了优化

如何使用插件

1. 依赖引入

由于这是一个针对鸿蒙平台的自定义修改版本,需要通过Git形式引入。在项目的pubspec.yaml文件中添加以下配置:

dependencies:
  flutter:
    sdk: flutter
  dio:
    git:
      url: "https://atomgit.com/"
      path: "packages/dio/dio"
  path_provider_ohos:
    git:
      url: "https://atomgit.com/"
      path: "packages/path_provider/path_provider"
  permission_handler:
    git:
      url: "https://atomgit.com/"
      path: "packages/permission_handler/permission_handler"

2. 网络权限配置

在鸿蒙项目的module.json5文件中添加网络访问权限:

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "Dio Test Application",
    "mainElement": "EntryAbility",
    "deviceTypes": ["phone", "tablet"],
    "distro": {
      "deliveryWithInstall": true,
      "moduleName": "entry",
      "moduleType": "entry"
    },
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "Dio Test Entry Ability",
        "icon": "$media:icon",
        "label": "Dio Test",
        "startWindowIcon": "$media:icon",
        "startWindowBackground": "$color:start_window_background",
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.READ_MEDIA"
      },
      {
        "name": "ohos.permission.WRITE_MEDIA"
      }
    ]
  }
}

3. 基本使用

初始化Dio
import 'package:dio/dio.dart';

// 创建Dio实例
final dio = Dio();

// 配置基础URL
 dio.options.baseUrl = 'https://api.example.com';

// 配置超时时间
 dio.options.connectTimeout = Duration(seconds: 5);
 dio.options.receiveTimeout = Duration(seconds: 3);
发送GET请求
Future<void> fetchData() async {
  try {
    final response = await dio.get('/data');
    print('Response data: ${response.data}');
    print('Status code: ${response.statusCode}');
  } catch (e) {
    print('Error: $e');
  }
}
发送POST请求
Future<void> sendData() async {
  try {
    final response = await dio.post('/submit', data: {
      'name': 'Flutter',
      'platform': 'OpenHarmony'
    });
    print('Response: ${response.data}');
  } catch (e) {
    print('Error: $e');
  }
}

4. 高级特性

拦截器
// 添加请求拦截器
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    // 在请求发送前做一些处理
    options.headers['Authorization'] = 'Bearer token';
    print('Request: ${options.path}');
    return handler.next(options);
  },
  onResponse: (response, handler) {
    // 对响应数据进行处理
    print('Response: ${response.statusCode}');
    return handler.next(response);
  },
  onError: (error, handler) {
    // 处理错误
    print('Error: ${error.message}');
    return handler.next(error);
  }
));
请求取消
Future<void> cancelableRequest() async {
  final cancelToken = CancelToken();

  try {
    // 发送请求
    final response = await dio.get(
      '/long-request',
      cancelToken: cancelToken
    );
    print('Response: ${response.data}');
  } catch (e) {
    if (CancelToken.isCancel(e)) {
      print('Request canceled');
    } else {
      print('Error: $e');
    }
  }

  // 在需要时取消请求
  // cancelToken.cancel('Cancel reason');
}
FormData和文件上传
Future<void> uploadFile() async {
  try {
    final formData = FormData.fromMap({
      'name': 'Test File',
      'file': await MultipartFile.fromFile('path/to/file.txt', filename: 'file.txt')
    });

    final response = await dio.post('/upload', data: formData);
    print('Upload response: ${response.data}');
  } catch (e) {
    print('Error: $e');
  }
}
文件下载
Future<void> downloadFile() async {
  try {
    final response = await dio.download(
      'https://example.com/file.pdf',
      'path/to/save/file.pdf'
    );
    print('Download completed');
  } catch (e) {
    print('Error: $e');
  }
}

5. 测试环境配置

在开发和测试阶段,可以配置Dio忽略SSL证书验证(仅用于测试环境):

import 'dart:io';

class GlobalHttpOverrides extends HttpOverrides {
  
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

// 在main函数中设置
void main() {
  HttpOverrides.global = GlobalHttpOverrides();
  runApp(MyApp());
}

完整示例

以下是一个完整的使用Dio的Flutter页面示例:

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioExamplePage extends StatefulWidget {
  const DioExamplePage({Key? key}) : super(key: key);

  
  State<DioExamplePage> createState() => _DioExamplePageState();
}

class _DioExamplePageState extends State<DioExamplePage> {
  final dio = Dio();
  String _result = 'Click button to make request';

  
  void initState() {
    super.initState();

    // 配置Dio
    dio.options.baseUrl = 'https://jsonplaceholder.typicode.com';
    dio.options.connectTimeout = Duration(seconds: 5);
    dio.options.receiveTimeout = Duration(seconds: 3);

    // 添加拦截器
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print('Request: ${options.method} ${options.path}');
        return handler.next(options);
      },
      onResponse: (response, handler) {
        print('Response: ${response.statusCode}');
        return handler.next(response);
      },
      onError: (error, handler) {
        print('Error: ${error.message}');
        return handler.next(error);
      }
    ));
  }

  Future<void> _fetchData() async {
    setState(() {
      _result = 'Loading...';
    });

    try {
      final response = await dio.get('/posts/1');
      setState(() {
        _result = 'Title: ${response.data['title']}\nBody: ${response.data['body']}';
      });
    } catch (e) {
      setState(() {
        _result = 'Error: $e';
      });
    }
  }

  Future<void> _submitData() async {
    setState(() {
      _result = 'Submitting...';
    });

    try {
      final response = await dio.post('/posts', data: {
        'title': 'Test Post',
        'body': 'This is a test post from Flutter on OpenHarmony',
        'userId': 1
      });
      setState(() {
        _result = 'Post created! ID: ${response.data['id']}';
      });
    } catch (e) {
      setState(() {
        _result = 'Error: $e';
      });
    }
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dio Example on OpenHarmony'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
              onPressed: _fetchData,
              child: const Text('Fetch Data'),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _submitData,
              child: const Text('Submit Data'),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: SingleChildScrollView(
                child: Text(_result),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

总结

dio作为一款成熟的HTTP客户端库,在开源鸿蒙平台上的适配为Flutter开发者提供了强大的网络请求能力。通过本指南,开发者可以快速上手使用dio进行网络请求、文件上传下载、请求拦截等操作。

该库的主要优势包括:

  1. 功能全面:涵盖了几乎所有网络请求场景
  2. 易于使用:简洁的API设计,降低学习成本
  3. 高度可扩展:通过拦截器可以灵活扩展功能
  4. 鸿蒙适配:针对鸿蒙平台进行了优化,确保稳定运行

使用dio可以帮助开发者在OpenHarmony平台上高效地构建网络应用,实现"一次开发,多端部署"的跨平台开发目标。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐