Flutter网络请求插件micro_core_http的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter网络请求插件micro_core_http的使用

micro_core_http 是一个基于 dio 包的封装,提供了一些开箱即用的功能。以下是该插件的详细说明和使用示例。

依赖

在你的 pubspec.yaml 文件中添加 micro_core_http 依赖:

dependencies:
  micro_core_http: ^版本号

平台支持

Android iOS MacOS Web Linux Windows

特性

  • 基本HTTP请求(DELETE, GET, PATCH, POST, PUT)
  • 请求的授权和日志记录可以轻松实现并有序地管理
  • 设置重试次数和重试间隔的重试请求
  • 实现拦截器以刷新授权令牌

即将推出

  • 支持下载请求并传递要下载文件的路径
  • 重试请求流程的改进
  • 刷新令牌拦截器的改进,使其更容易实现

使用

基本用法

以下是一个基本用法的示例:

import 'package:micro_core_http/micro_core_http.dart';

// 定义授权处理器
final class AppHttpAuthorizationHandler implements IHttpAuthorizationHandler {
  // 本地存储实例

  const AppHttpAuthorizationHandler();

  // 定义在何处添加令牌
  [@override](/user/override)
  HttpAuthorizationType get authorizationType => HttpAuthorizationType.headers;

  [@override](/user/override)
  Future<Map<String, String>> getAuthorization() async {
    // 使用本地存储实例返回授权令牌
    return {
      'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjMiLCJ1c2VybmFtZSI6IjE1NDk0NDkzNzA5IiwiZW1haWwiOiJqcDk4c21hcnRpbnNAZ21haWwuY29tIiwiaXAiOjAsImxvZ2luX3Rva2VuIjoib2trbGFlb2lxamg0N3p4bDU2bG8yIiwidHlwZSI6IkFQUCIsImlhdCI6MTcwMjk4OTIyMywiZXhwIjoxNzAyOTkyODIzfQ.pNqx0JTt9FC7xkGMHgcLZE1Ln71nTnhC-qpOXlYPfGM',
    };
  }
}

// 定义仓库类
final class Repository {
  final IHttpClient api;

  const Repository(this.api);

  Future<Map<String, dynamic>> getPackagesList() async {
    try {
      // 实现请求
      final response = await api.get(
        '/packages',
        segment: 'Packages',
        step: 'Getting Packages List',
      );

      // 返回响应
      return Map<String, dynamic>.from(response.data);
    } on HttpException catch (exception) {
      // 处理基本/自定义异常
      if (exception is HttpExceptionUnauthorized) {
        print('User is Unauthorized!');
      }
      rethrow;
    }
  }
}

// 定义控制器类
class Controller {
  final Repository _repository;

  const Controller(this._repository);

  Future<void> getPackagesList() async {
    final result = await _repository.getPackagesList();

    // 处理结果
    print(result.toString());
  }
}

void main() {
  // 配置选项
  final options = HttpOptions(
    authorizationHandler: AppHttpAuthorizationHandler(),
    baseUrl: "https://api.jotapetecnologia.com.br",
    delayBetweenRetries: Duration(seconds: 2),
    requestTimeout: Duration(seconds: 8),
    extraRetries: 2,
    showLogs: true,
  );
  
  // 创建客户端
  final api = HttpClient(options: options);
  final repository = Repository(api);
  final controller = Controller(repository);

  // 执行请求
  controller.getPackagesList();
}

适配器用法

以下是如何使用适配器的示例:

import 'package:micro_core_http/micro_core_http.dart';

// 定义默认HTTP选项
final class DefaultHttpOptions {
  late final HttpOptions _options;
  HttpOptions get options => _options;

  DefaultHttpOptions(IHttpAuthorizationHandler authorizationHandler) {
    _options = HttpOptions(
      authorizationHandler: authorizationHandler,
      baseUrl: 'https://api.jotapetecnologia.com.br',
      delayBetweenRetries: const Duration(seconds: 2),
      responseHandler: HttpResponseHandler(),
      extraRetries: 2,
      requestTimeout: const Duration(seconds: 12),
      showLogs: true,
    );
  }
}

// 定义HTTP适配器接口
abstract interface class IHttpAdapter {
  Future<HttpResponse> delete(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  });

  Future<HttpResponse> get(
    String endpoint, {
    bool authenticate = false,
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  });

  Future<HttpResponse> patch(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  });

  Future<HttpResponse> post(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  });

  Future<HttpResponse> put(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  });
}

// 定义授权处理器
final class AppHttpAuthorizationHandler implements IHttpAuthorizationHandler {
  // 本地存储实例

  const AppHttpAuthorizationHandler();

  // 定义在何处添加令牌
  [@override](/user/override)
  HttpAuthorizationType get authorizationType => HttpAuthorizationType.headers;

  [@override](/user/override)
  Future<Map<String, String>> getAuthorization() async {
    // 使用本地存储实例返回授权令牌
    return {
      'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjMiLCJ1c2VybmFtZSI6IjE1NDk0NDkzNzA5IiwiZW1haWwiOiJqcDk4c21hcnRpbnNAZ21haWwuY29tIiwiaXAiOjAsImxvZ2luX3Rva2VuIjoib2trbGFlb2lxamg0N3p4bDU2bG8yIiwidHlwZSI6IkFQUCIsImlhdCI6MTcwMjk4OTIyMywiZXhwIjoxNzAyOTkyODIzfQ.pNqx0JTt9FC7xkGMHgcLZE1Ln71nTnhC-qpOXlYPfGM',
    };
  }
}

// 定义响应处理器
final class HttpResponseHandler implements IHttpResponseHandler {
  [@override](/user/override)
  void logResponse(HttpResponse response) {
    if (response.statusCode > 199 && response.statusCode < 300) {
      // return Logger.logSuccess(response.toString());
    }

    // return Logger.logWarning(response.toString());
  }

  [@override](/user/override)
  void onResponse(HttpResponse response) {}
}

// 定义HTTP适配器
final class HttpAdapter implements IHttpAdapter {
  final HttpOptions options;

  const HttpAdapter(this.options);

  static const Map<String, String> defaultHeaders = {
    "accept": "*/*",
    "content-type": "application/json",
  };

  [@override](/user/override)
  Future<HttpResponse> delete(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers = defaultHeaders,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  }) {
    final client = HttpClient(
      options: options,
    );

    return client.delete(
      endpoint,
      authenticate: authenticate,
      body: body,
      headers: headers,
      queryParameters: queryParameters,
      replaceBaseUrl: replaceBaseUrl,
      segment: segment,
      step: step,
    );
  }

  [@override](/user/override)
  Future<HttpResponse> get(
    String endpoint, {
    bool authenticate = false,
    Map<String, String>? headers = defaultHeaders,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  }) {
    final client = HttpClient(
      options: options,
    );

    return client.get(
      endpoint,
      authenticate: authenticate,
      headers: headers,
      queryParameters: queryParameters,
      replaceBaseUrl: replaceBaseUrl,
      segment: segment,
      step: step,
    );
  }

  [@override](/user/override)
  Future<HttpResponse> patch(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers = defaultHeaders,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  }) {
    final client = HttpClient(
      options: options,
    );

    return client.patch(
      endpoint,
      authenticate: authenticate,
      body: body,
      headers: headers,
      queryParameters: queryParameters,
      replaceBaseUrl: replaceBaseUrl,
      segment: segment,
      step: step,
    );
  }

  [@override](/user/override)
  Future<HttpResponse> post(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers = defaultHeaders,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  }) {
    final client = HttpClient(
      options: options,
    );

    return client.post(
      endpoint,
      authenticate: authenticate,
      body: body,
      headers: headers,
      queryParameters: queryParameters,
      replaceBaseUrl: replaceBaseUrl,
      segment: segment,
      step: step,
    );
  }

  [@override](/user/override)
  Future<HttpResponse> put(
    String endpoint, {
    bool authenticate = false,
    dynamic body,
    Map<String, String>? headers = defaultHeaders,
    Map<String, dynamic>? queryParameters,
    String? replaceBaseUrl,
    String? segment,
    String? step,
  }) {
    final client = HttpClient(
      options: options,
    );

    return client.put(
      endpoint,
      authenticate: authenticate,
      body: body,
      headers: headers,
      queryParameters: queryParameters,
      replaceBaseUrl: replaceBaseUrl,
      segment: segment,
      step: step,
    );
  }
}

// 使用适配器的示例
final class Repository {
  final IHttpAdapter api;

  const Repository(this.api);

  Future<Map<String, dynamic>> getPackagesList() async {
    try {
      // 实现请求
      final response = await api.get(
        '/packages',
        segment: 'Packages',
        step: 'Getting Packages List',
      );

      // 返回响应
      return Map<String, dynamic>.from(response.data);
    } on HttpException catch (exception) {
      // 处理基本/自定义异常
      if (exception is HttpExceptionUnauthorized) {
        print('User is Unauthorized!');
      }
      rethrow;
    }
  }
}

class Controller {
  final Repository _repository;

  const Controller(this._repository);

  Future<void> getPackagesList() async {
    final result = await _repository.getPackagesList();

    // 处理结果
    print(result.toString());
  }
}

void main() {
  final authorizationHandler = AppHttpAuthorizationHandler();
  final defaultOptions = DefaultHttpOptions(authorizationHandler);
  final api = HttpAdapter(defaultOptions.options);
  final repository = Repository(api);
  final controller = Controller(repository);

  controller.getPackagesList();
}

更多关于Flutter网络请求插件micro_core_http的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络请求插件micro_core_http的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用micro_core_http插件进行网络请求的示例代码。micro_core_http是一个轻量级的Flutter HTTP客户端插件,用于简化网络请求。

首先,确保你已经在pubspec.yaml文件中添加了micro_core_http依赖项:

dependencies:
  flutter:
    sdk: flutter
  micro_core_http: ^最新版本号  # 请替换为实际最新版本号

然后运行flutter pub get来安装依赖。

接下来是一个简单的示例,展示如何使用micro_core_http发送GET和POST请求。

1. 导入插件

在你的Dart文件中导入micro_core_http

import 'package:micro_core_http/micro_core_http.dart';
import 'dart:convert';

2. 发送GET请求

void fetchData() async {
  try {
    // 创建HttpClient实例
    var client = HttpClient();
    
    // 定义请求的URL
    var url = Uri.parse('https://api.example.com/data');
    
    // 发送GET请求
    var response = await client.get(url);
    
    // 检查响应状态码
    if (response.statusCode == 200) {
      // 读取响应体
      var responseBody = await response.transform(utf8.decoder).join();
      
      // 解析JSON数据
      var data = jsonDecode(responseBody);
      
      // 处理数据
      print(data);
    } else {
      print('请求失败,状态码:${response.statusCode}');
    }
  } catch (e) {
    print('请求过程中发生错误:$e');
  }
}

3. 发送POST请求

void postData() async {
  try {
    // 创建HttpClient实例
    var client = HttpClient();
    
    // 定义请求的URL
    var url = Uri.parse('https://api.example.com/submit');
    
    // 创建请求体(JSON数据)
    var body = jsonEncode({'key1': 'value1', 'key2': 'value2'});
    
    // 发送POST请求并附带请求头
    var request = await client.postUrl(url);
    request.headers.contentType = ContentType.parse('application/json');
    request.write(body);
    
    // 获取响应
    var response = await request.close();
    
    // 检查响应状态码
    if (response.statusCode == 200 || response.statusCode == 201) {
      // 读取响应体
      var responseBody = await response.transform(utf8.decoder).join();
      
      // 解析JSON数据
      var data = jsonDecode(responseBody);
      
      // 处理数据
      print(data);
    } else {
      print('请求失败,状态码:${response.statusCode}');
    }
  } catch (e) {
    print('请求过程中发生错误:$e');
  }
}

4. 使用示例

你可以在你的Flutter应用中的任何位置调用这些函数,例如在按钮点击事件中:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('micro_core_http 示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: fetchData,
                child: Text('发送 GET 请求'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: postData,
                child: Text('发送 POST 请求'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何在Flutter应用中使用micro_core_http插件发送GET和POST请求。请注意,实际使用时,你需要根据API的要求调整URL和请求数据。

回到顶部