Flutter网络请求插件http4的使用

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

Flutter网络请求插件http4的使用

http4 包在 Flutter 中提供了增强的 HTTP 请求功能,通过利用 http 包和 http_interceptor 来实现可定制的 HTTP 请求,并具有额外的功能和新的调用方式。

特性

  • HTTP 方法:简化了 HTTP 方法(GET、POST、PUT、PATCH、DELETE、MULTIPART),并支持自定义的头部信息、参数和重试策略。
  • HTTP 拦截器:能够使用拦截器来修改请求头部、日志记录以及重试失败的请求。
  • 配置基础 URL:可以为包内的所有 HTTP 请求配置基础 URL。
  • 调试模式:启用调试模式以打印关于 HTTP 请求和异常的详细信息。

安装

http4 添加到你的 pubspec.yaml 文件中:

dependencies:
    http4: ^0.0.4

使用方法

1. 第一种方式
import 'package:http4/http4.dart';

void fetchData() async {
  final http4 = Http4();

  final response = await http4.get(
    '/api/data',
    headers: {'Authorization': 'Bearer <token>'},
    params: {'page': 1},
    retryPolicy: RetryOptions(maxAttempts: 3),
  );

  if (response.isSuccessed && response.isOkey) {
    // 处理成功的响应
    print('Response: ${response.decodedBody}');
  } else {
    // 处理失败的响应
    print('Request failed');
  }
}
2. 第二种方式(继承自 Http4)
import 'package:http4/http4.dart' as http4;

class ExampleService extends http4.Http4 {
  Future<List<Map<String, dynamic>>> fetchData() async {
    final response = await get(
      '/posts?_page=1&_per_page=10',
      interceptors: [AuthInterceptor()],
    );

    return response.decodedBody;
  }
}
如何使用拦截器
import 'package:http4/http4.dart' as http4;

class ExampleService extends http4.Http4 {
  Future<List<Map<String, dynamic>>> fetchData() async {
    final response = await get(
      '/posts?_page=1&_per_page=10',
      interceptors: [
        AuthInterceptor(token: 'Your-Token-Here'),
      ],
    );

    return response.decodedBody;
  }
}

class AuthInterceptor extends http4.InterceptorContract {
  late String token;

  AuthInterceptor({
    required this.token,
  });

  @override
  Future<http4.BaseRequest> interceptRequest({required http4.BaseRequest request}) {
    request.headers.addAll({'Authorization': 'Bearer $token'});

    // 在发送请求之前,将 Authorization 添加到头部
    return Future.value(request);
  }

  @override
  Future<http4.BaseResponse> interceptResponse({required http4.BaseResponse response}) {
    if (response.statusCode == 401) {
      print('Unauthorized request');
      // 调用请求之后,会重定向到登录页面
    }

    return Future.value(response);
  }
}

配置

要配置基础 URL 和调试模式,可以使用 Http4Config

final config = Http4Config();
config.baseUrl = 'https://api.example.com';
config.debugMode = true;

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用http包(注意:http4并不是一个广泛认可的Flutter插件,通常我们使用的是http包)来进行网络请求的示例代码。这个示例将展示如何发送GET和POST请求,并处理响应。

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

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3  # 请检查最新版本号并更新

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

接下来是一个简单的Flutter应用示例,展示如何使用http包进行网络请求:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter HTTP Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _responseText = '';

  void _makeGetRequest() async {
    try {
      var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
      if (response.statusCode == 200) {
        setState(() {
          _responseText = jsonDecode(response.body).toString();
        });
      } else {
        setState(() {
          _responseText = 'Error: ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _responseText = 'Error: $e';
      });
    }
  }

  void _makePostRequest() async {
    try {
      var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
      var body = jsonEncode(<String, dynamic>{
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      });

      var response = await http.post(url,
          headers: <String, String>{
            'Content-Type': 'application/json',
          },
          body: body);

      if (response.statusCode == 201) {
        setState(() {
          _responseText = jsonDecode(response.body).toString();
        });
      } else {
        setState(() {
          _responseText = 'Error: ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _responseText = 'Error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter HTTP Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Response:', style: TextStyle(fontSize: 18)),
            SizedBox(height: 16),
            Expanded(
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Text(_responseText, style: TextStyle(fontSize: 16)),
              ),
            ),
            SizedBox(height: 24),
            Row(
              children: <Widget>[
                Expanded(
                  child: ElevatedButton(
                    onPressed: _makeGetRequest,
                    child: Text('Make GET Request'),
                  ),
                ),
                SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _makePostRequest,
                    child: Text('Make POST Request'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

代码说明:

  1. 依赖管理:在pubspec.yaml中添加http依赖。
  2. GET请求_makeGetRequest方法使用http.get发送一个GET请求到https://jsonplaceholder.typicode.com/posts/1,并处理响应。
  3. POST请求_makePostRequest方法使用http.post发送一个POST请求到https://jsonplaceholder.typicode.com/posts,并包含JSON格式的数据。
  4. UI:使用Flutter的Material组件构建了一个简单的UI,显示响应文本并提供两个按钮来触发GET和POST请求。

这个示例展示了如何在Flutter应用中集成和使用http包进行基本的网络请求。记得在实际应用中处理更多的错误情况和边界条件。

回到顶部