一. 网络请求的方式

在Flutter中常见的网络请求方式有三种:HttpClient、http库、dio库;

1.1. HttpClient

HttpClient是dart自带的请求类,在io包中,实现了基本的网络请求相关的操作。
网络调用通常遵循如下步骤:

  1. 创建 client.
  2. 构造 Uri.
  3. 发起请求, 等待请求,同时您也可以配置请求headers、 body。
  4. 关闭请求, 等待响应.
  5. 解码响应的内容.

网络请求实例:

  1. void requestNetwork() async {
  2. // 1.创建HttpClient对象
  3. final httpClient = HttpClient();
  4. // 2.构建请求的uri
  5. final uri = Uri.parse("http://123.207.32.32:8000/api/v1/recommend");
  6. // 3.构建请求
  7. final request = await httpClient.getUrl(uri);
  8. // 4.发送请求,必须
  9. final response = await request.close();
  10. if (response.statusCode == HttpStatus.ok) {
  11. print(await response.transform(utf8.decoder).join());
  12. } else {
  13. print(response.statusCode);
  14. }
  15. }

1.2. http库

http 是 Dart 官方提供的另一个网络请求类,相比于 HttpClient,易用性提升了不少。
但是,没有默认集成到Dart的SDK中,所以我们需要先在pubspec中依赖它:
http:^0.12.0+2

  1. import'package:http/http.dart'as http;
  2. void httpNetwork() async {
  3. // 1.创建Client
  4. final client = http.Client();
  5. // 2.构建uri
  6. final url = Uri.parse("http://123.207.32.32:8000/api/v1/recommend");
  7. // 3.发送请求
  8. final response = await client.get(url);
  9. // 4.获取结果
  10. if (response.statusCode == HttpStatus.ok) {
  11. print(response.body);
  12. } else {
  13. print(response.statusCode);
  14. }
  15. }

1.3. dio三方库

对于现代开发来说,要求的东西会更多:比如拦截器、取消请求、文件上传/下载、超时设置等等;
dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等…
使用dio三方库必然也需要先在pubspec中依赖它:
dio:^3.0.1

  1. import'package:dio/dio.dart';
  2. void dioNetwork() async {
  3. // 1.创建Dio请求对象
  4. final dio = Dio();
  5. // 2.发送网络请求
  6. final response = await dio.get("http://123.207.32.32:8000/api/v1/recommend");
  7. // 3.打印请求结果
  8. if (response.statusCode == HttpStatus.ok) {
  9. print(response.data);
  10. } else {
  11. print("请求失败:${response.statusCode}");
  12. }
  13. }

1.4. dio库的封装

  1. http_config.dart
  2. class HTTPConfig {
  3. staticconst baseURL = "https://httpbin.org";
  4. staticconst timeout = 5000;
  5. }
  6. http_request.dart
  7. import'package:dio/dio.dart';
  8. import'package:testflutter001/service/config.dart';
  9. class HttpRequest {
  10. staticfinal BaseOptions options = BaseOptions(
  11. baseUrl: HTTPConfig.baseURL, connectTimeout: HTTPConfig.timeout);
  12. staticfinal Dio dio = Dio(options);
  13. static Future<T> request<T>(String url,
  14. {String method = 'get', Map<String, dynamic> params, Interceptor inter}) async {
  15. // 1.请求的单独配置
  16. final options = Options(method: method);
  17. // 2.添加第一个拦截器
  18. Interceptor dInter = InterceptorsWrapper(
  19. onRequest: (RequestOptions options) {
  20. // 1.在进行任何网络请求的时候, 可以添加一个loading显示
  21. // 2.很多页面的访问必须要求携带Token,那么就可以在这里判断是有Token
  22. // 3.对参数进行一些处理,比如序列化处理等
  23. print("拦截了请求");
  24. return options;
  25. },
  26. onResponse: (Response response) {
  27. print("拦截了响应");
  28. return response;
  29. },
  30. onError: (DioError error) {
  31. print("拦截了错误");
  32. return error;
  33. }
  34. );
  35. List<Interceptor> inters = [dInter];
  36. if (inter != null) {
  37. inters.add(inter);
  38. }
  39. dio.interceptors.addAll(inters);
  40. // 3.发送网络请求
  41. try {
  42. Response response = await dio.request<T>(url, queryParameters: params, options: options);
  43. return response.data;
  44. } on DioError catch(e) {
  45. return Future.error(e);
  46. }
  47. }
  48. }

代码使用:

  1. HttpRequest.request("https://httpbin.org/get", params: {"name": "wulei", 'age': 18})
  2. .then((res) {
  3. print(res);
  4. });
  5. HttpRequest.request("https://httpbin.org/post", method: "post", params: {"name": "why", 'age': 18})
  6. .then((res) {
  7. print(res);
  8. });