Flutter网络请求插件easy_request的使用

Flutter网络请求插件easy_request的使用

Easy Request 使得执行 HTTP 请求变得简单。

特性

  • GET 请求
  • POST 请求
  • PUT 请求
  • DELETE 请求

开始使用

Http 包用于发起 HTTP 请求。

使用示例

import 'package:easy_request/easy_request.dart' show request;

void main() async {
  // GET 请求
  final dynamic getData = 
      await request(url: 'https://reqres.in/api/users?page=2');
  // print(getData);

  // POST 请求 => 如果服务器返回响应,它将可用在 postData 变量中
  final dynamic postData = await request(
      url: 'https://reqres.in/api/users?page=2',
      method: 'POST',
      // headers: {'Content-Type': 'application/json'}, => 不需要设置此头部
      body: {'name': 'Example post request', 'job': 'Post data to reqRes'});
  // print(postData);

  // PUT 请求 => 和 POST 请求类似
  final dynamic putData = await request(
      url: 'https://reqres.in/api/users?page=2',
      method: 'PUT',
      body: {
        'name': 'Modified data',
        'job': 'Job has been updated to PUT job'
      });
  // print(putData);

  // DELETE 请求
  final deleteData = await request(
      url: 'https://reqres.in/api/users?page=2', method: 'DELETE');
  print('Delete: ${deleteData}');
}

示例代码

import 'package:easy_request/easy_request.dart' show request;

void main() async {
  // GET 请求
  final dynamic getData = 
      await request(url: 'https://reqres.in/api/users?page=2');
  // print(getData);

  // POST 请求 => 如果服务器返回响应,它将可用在 postData 变量中
  final dynamic postData = await request(
      url: 'https://reqres.in/api/users?page=2',
      method: 'POST',
      // headers: {'Content-Type': 'application/json'}, => 不需要设置此头部
      body: {'name': 'Example post request', 'job': 'Post data to reqRes'});
  // print(postData);

  // PUT 请求 => 和 POST 请求类似
  final dynamic putData = await request(
      url: 'https://reqres.in/api/users?page=2',
      method: 'PUT',
      body: {
        'name': 'Modified data',
        'job': 'Job has been updated to PUT job'
      });
  // print(putData);

  // DELETE 请求
  final deleteData = await request(
      url: 'https://reqres.in/api/users?page=2', method: 'DELETE');
  print('Delete: ${deleteData}');
}

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

1 回复

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


easy_request 是一个用于简化 Flutter 网络请求的插件。它提供了一种简单的方式来发送 HTTP 请求,并且支持异步操作、错误处理和响应解析等功能。以下是如何在 Flutter 项目中使用 easy_request 的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 easy_request 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  easy_request: ^1.0.0  # 请使用最新版本

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

2. 导入包

在你的 Dart 文件中导入 easy_request

import 'package:easy_request/easy_request.dart';

3. 发送请求

使用 easy_request 发送 HTTP 请求非常简单。以下是一些常见的请求示例:

GET 请求

void fetchData() async {
  try {
    var response = await EasyRequest.get('https://jsonplaceholder.typicode.com/posts');
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

POST 请求

void postData() async {
  try {
    var response = await EasyRequest.post(
      'https://jsonplaceholder.typicode.com/posts',
      body: {
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      },
    );
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

PUT 请求

void updateData() async {
  try {
    var response = await EasyRequest.put(
      'https://jsonplaceholder.typicode.com/posts/1',
      body: {
        'id': 1,
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      },
    );
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

DELETE 请求

void deleteData() async {
  try {
    var response = await EasyRequest.delete('https://jsonplaceholder.typicode.com/posts/1');
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  } catch (e) {
    print('Error: $e');
  }
}

4. 处理响应

EasyRequest 返回的响应对象包含了状态码、响应头和响应体等信息。你可以根据需要处理这些数据。

void handleResponse(Response response) {
  if (response.statusCode == 200) {
    print('Request successful');
    print('Response body: ${response.body}');
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

5. 错误处理

EasyRequest 会自动处理一些常见的网络错误,但你也可以在 try-catch 块中捕获并处理异常。

void fetchData() async {
  try {
    var response = await EasyRequest.get('https://jsonplaceholder.typicode.com/posts');
    handleResponse(response);
  } catch (e) {
    print('Error: $e');
  }
}

6. 配置请求

EasyRequest 允许你配置请求的头部、查询参数、超时时间等。

void fetchDataWithHeaders() async {
  try {
    var response = await EasyRequest.get(
      'https://jsonplaceholder.typicode.com/posts',
      headers: {
        'Authorization': 'Bearer your_token',
      },
      queryParameters: {
        'userId': 1,
      },
      timeout: Duration(seconds: 10),
    );
    handleResponse(response);
  } catch (e) {
    print('Error: $e');
  }
}
回到顶部