Flutter网络请求插件easy_http_request的使用

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

Flutter网络请求插件easy_http_request的使用

首先,欢迎来到通过简单方式消费服务的世界。

安装

添加依赖:

dependencies:
  easy_http: 1.0.2

初始化

首先,导入依赖:

import 'package:easy_http_request/easy_http_request.dart';

如果你只使用一个单一的API路径,可以这样做:

const String mainApiPath = 'MAIN_API';
EasyHttpSettings.initWithSingleApi(config: EasyHttpConfig(apiPath: 'https://jsonplaceholder.typicode.com', identifier: mainApiPath));

或者,如果你需要使用多个API路径,可以这样做:

const String firstIdentifier = 'FirstApiPath';
const String secondIdentifier = 'SecondApiPath';

EasyHttpSettings.initWithManyApi(config: [
    EasyHttpConfig(apiPath: 'https://jsonplaceholder.typicode.com', identifier: firstIdentifier),
    EasyHttpConfig(apiPath: 'https://fakestoreapi.com', identifier: secondIdentifier)
]);

你可以在主方法中添加初始化(例如):

const String mainApiPath = 'MAIN_API';

void main() {
  // 包初始化
  EasyHttpSettings.initWithSingleApi(config: EasyHttpConfig(apiPath: 'https://jsonplaceholder.typicode.com', identifier: mainApiPath));

  runApp(App());
}

HttpConfigData 还有更多属性,如:

HttpConfigData({
    required this.identifier,
    required this.apiPath,
    this.headers = const {},
    this.timeOut = 30 * 1000,
    this.validStatus = 204, 
    this.followRedirect = false,
    this.includeLogger = true,
});

int validStatus;
// 请求的合法状态码,表示请求完成或未完成。
// 例如:
// 如果你的服务返回了200 Ok, 201 Created 和 204 NotContent,
// 那么 [validStatusCode] 是这些状态码中的最大值,在本例中为204。
// 默认情况下,合法状态码是204 NotContent。

根据需要进行配置。

结合依赖注入

现在你可以:

  1. 使用 Getx 依赖注入:
class MainBindings implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut<EasyHttpRequestContract>(() => EasyHttpRequest());
  }
}
  1. 或者,你也可以使用 Get It:
class DIManager {
  static void setup() {
    final getIt = GetIt.instance;
    getIt.registerSingleton<EasyHttpRequestContract>(EasyHttpRequest());
  }
}
  1. 最后,你可以使用旧的方式:
final httpServices = EasyHttpRequest();

配置模型

模型需要实现 HttpDataParser,以便在调用方法时发送的数据类型有效。

这是一个我们经常使用的常见模型:

class PostModel {
  PostModel({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  int? userId;
  int? id;
  String? title;
  String? body;

  PostModel fromJson(Map<String, dynamic> json) => PostModel(
        userId: json['userId'],
        id: json['id'],
        title: json['title'],
        body: json['body'],
      );

  Map<String, dynamic> toJson() => {
        'userId': userId,
        'id': id,
        'title': title,
        'body': body,
      };
}

这是我们将要做的简单更改:

import 'package:easy_http_request/easy_http_request.dart';

class PostModel implements HttpDataParser<PostModel> {
  PostModel({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  int? userId;
  int? id;
  String? title;
  String? body;

  @override
  PostModel fromJson(Map<String, dynamic> json) => PostModel(
        userId: json['userId'],
        id: json['id'],
        title: json['title'],
        body: json['body'],
      );

  @override
  Map<String, dynamic> toJson() => {
        'userId': userId,
        'id': id,
        'title': title,
        'body': body,
      };
}

我们导入了包,实现了 HttpDataParser 并将我们正在配置的模型类型化:

class PostModel implements HttpDataParser<PostModel>{}

然后添加 @overridetoJsonfromJson 方法即可。

参数和响应数据

请求参数

  1. 用于请求的参数:
String extraUri 
/*
如果需要向基础API添加一些信息。 
例如:你的基础API是www.domain.com,你想查询www.domain.com/posts,
只需在 extraUri 中添加 posts 即可将其与基础API连接。
*/

T model
/*
你要使用的模型本身,在 getOne 或 getMany 中只发送一个模型实例,
例如:
*/

model: PostModel()

/*
如果是 onPost, onPut, onPatch,则发送包含创建或更新信息的模型实例。
例如:
*/

PostModel fakerModel = PostModel(
    id: 1,
    userId: faker.randomGenerator.integer(4000, min: 100),
    title: faker.company.name(),
    body: faker.lorem.sentences(4).join(' '),
);

// 然后,发送它
model: fakerModel

Map<String, dynamic> queryParams
/*
你可以使用它来发送通常直接包含在路由路径中的查询参数。 例如:
*/

queryParams: {
  "id":1, 
  "lang":"en"
}

bool returnModel
/*
在 onPost, onPut, onPatch 方法中,你可以选择返回模型,
如果你的服务返回刚刚创建或更新的记录。
默认情况下为false。
*/
  1. 响应值

EasyHttpRequestResponse 类有一些属性,根据所使用的方法不同而有所不同:

EasyHttpRequestResponse({
    this.completeResponse,
    this.modelResponse,
    this.modelResponseAsList,
  });
  • completeResponse => 直接来自HTTP客户端的回复。 包含 statusCode、headers 等
  • modelResponse => 返回适用的模型。 例如,在 onGetOne 中返回模型。 在 onPost, onPut 和 onPatch 中,取决于你的需求及服务是否返回模型
  • modelResponseAsList => 返回模型集合。 仅在 onGetMany 中返回值

示例

HTTP请求

有两种请求方法:

  1. 使用单个HTTP客户端。
final response = await easyHttpInstance.requestWithSinglePATH<PostModel>(
  model: PostModel(), 
  requestType: EasyHttpType.getSingle, 
  extraUri: '$_extraUri/$id'
);
  1. 使用客户集合中的一个。
final response = await easyHttpInstance.requestWithManyPATH<PostModel>(
  model: PostModel(),
  identifier: firstIdentifier,
  requestType: EasyHttpType.getSingle,
  extraUri: 'posts/1',
);

执行不同类型的请求只需使用 EasyHttpType,它允许你选择请求类型:

// getSingle:
final response = await easyHttpInstance.requestWithSinglePATH<PostModel>(model: PostModel(), requestType: EasyHttpType.getSingle, extraUri: '$_extraUri/$id');

// getCollection
final response = await easyHttpInstance.requestWithSinglePATH<PostModel>(model: PostModel(), requestType: EasyHttpType.getCollection, extraUri: _extraUri);

// post
final response =
          await easyHttpInstance.requestWithSinglePATH<PostModel>(model: fakerModel, requestType: EasyHttpType.post, extraUri: _extraUri, returnModel: true);

// put
final response = await easyHttpInstance.requestWithSinglePATH<PostModel>(
          model: fakerModel, requestType: EasyHttpType.put, extraUri: '$_extraUri/${fakerModel.id}', returnModel: true);

// patch
final response = await easyHttpInstance.requestWithSinglePATH<PostModel>(
          model: fakerModel, requestType: EasyHttpType.patch, extraUri: '$_extraUri/${fakerModel.id}', returnModel: true);

// delete
final response = await easyHttpInstance.requestWithSinglePATH<PostModel>(model: PostModel(), requestType: EasyHttpType.delete, extraUri: '$_extraUri/$id');

如果你使用的是多个HTTP客户端,只需这样做:

// getSingle:
final response = await easyHttpInstance.requestWithManyPATH<PostModel>(
          model: PostModel(),// 模型
          identifier: firstIdentifier, // 包含实例标识符
          requestType: EasyHttpType.getSingle, // 请求类型
          extraUri: 'posts/1',
        );

管理头信息

一旦HTTP客户端被实例化,你可以修改它们的头信息:

  • 对于单个HTTP客户端:
// 添加头信息
EasyHeadersManager.addHeadersSingleClient(newHeaders: {'jwt': 'qwertyuiop', 'api_key': 'iuqhjnudh87asyd8a7ys7ds'});
// 更新头信息
EasyHeadersManager.updateHeadersSingleClient(key: 'jwt', value: 'poiuytrewq');
// 移除头信息
EasyHeadersManager.removeHeadersSingleClient(key: 'jwt');
  • 对于多个HTTP客户端,你只需要添加标识符字段,这将帮助识别哪个HTTP客户端实例的头信息将被修改:
// 添加头信息
EasyHeadersManager.addHeadersManyClient(identifier: firstIdentifier, newHeaders: {'jwt': 'qwertyuiop', 'api_key': 'iuqhjnudh87asyd8a7ys7ds'});

// 更新头信息
EasyHeadersManager.updateHeadersManyClient(identifier: secondIdentifier, key: 'api_key', value: '174091u1j2e091j2');

// 移除头信息
EasyHeadersManager.removeHeadersManyClient(identifier: secondIdentifier, key: 'jwt');

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

1 回复

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


当然,我可以为你提供一个关于如何使用Flutter网络请求插件easy_http_request的代码案例。以下是一个简单的示例,展示了如何配置和使用该插件进行网络请求。

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

dependencies:
  flutter:
    sdk: flutter
  easy_http_request: ^最新版本号  # 请替换为最新版本号

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

接下来,创建一个Flutter项目(如果还没有的话),并在项目中进行以下配置和使用。

1. 配置EasyHttpRequest

main.dart或你选择的初始化文件中,配置EasyHttpRequest

import 'package:flutter/material.dart';
import 'package:easy_http_request/easy_http_request.dart';

void main() {
  // 配置EasyHttpRequest
  EasyHttpRequest.instance
    ..baseUrl = "https://api.example.com"  // 替换为你的API基础URL
    ..timeout = Duration(seconds: 10)      // 设置请求超时时间
    ..headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      // 添加其他需要的头部信息
    };

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

2. 使用EasyHttpRequest进行GET请求

HomeScreen或其他页面中,使用EasyHttpRequest进行GET请求:

import 'package:flutter/material.dart';
import 'package:easy_http_request/easy_http_request.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String responseData = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('EasyHttpRequest Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Response Data:'),
            Text(responseData),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _fetchData,
              child: Text('Fetch Data'),
            ),
          ],
        ),
      ),
    );
  }

  void _fetchData() async {
    try {
      var response = await EasyHttpRequest.instance.get("/endpoint");  // 替换为你的API端点
      setState(() {
        responseData = response.data.toString();
      });
    } catch (e) {
      print("Error fetching data: $e");
      setState(() {
        responseData = "Error fetching data";
      });
    }
  }
}

3. 使用EasyHttpRequest进行POST请求

同样地,你可以使用post方法进行POST请求,并传递请求体:

void _postData() async {
  try {
    var body = {
      'key1': 'value1',
      'key2': 'value2',
      // 添加其他请求参数
    };

    var response = await EasyHttpRequest.instance.post("/endpoint", body: body);  // 替换为你的API端点
    setState(() {
      responseData = response.data.toString();
    });
  } catch (e) {
    print("Error posting data: $e");
    setState(() {
      responseData = "Error posting data";
    });
  }
}

你可以在HomeScreen中添加一个按钮来触发_postData方法:

ElevatedButton(
  onPressed: _postData,
  child: Text('Post Data'),
),

这样,你就完成了使用easy_http_request插件进行网络请求的示例。这个示例展示了如何配置插件、进行GET和POST请求,并处理响应数据。你可以根据实际需求进一步扩展和优化代码。

回到顶部