flutter http请求的几种方式

目录

  • 1.Http
  • 2.HttpClient
  • 3.Dio
  • 4.json to Dart json数据转换成bean

1.Http

  1. 导入依赖
dependencies:
  http: ^0.12.1
  1. 代码书写

然后在代码里加入

import 'package:http/http.dart' as http;
  http.get("https://www.wanandroid.com/tree/json").then((value) {

      print("test-http  ${value.statusCode}");
      print("test-http content ${value.body}");

    });
  1. 日志打印
    flutter http请求的几种方式_第1张图片

2.HttpClient

1.导入包

import 'dart:convert';
import 'dart:io';

2.代码

  void testHttp() async{

    HttpClient httpClient = HttpClient();
   HttpClientRequest  httpClientRequest = await httpClient.getUrl(Uri.parse("https://www.wanandroid.com/tree/json"));
   HttpClientResponse  response = await httpClientRequest.close();

   var result = await response.transform(utf8.decoder).join();

   print("uuu=${result}");

   httpClient.close();
}

3.日志

在这里插入图片描述

3.Dio

dio 很强大,支持Restful API FormData、拦截器、请求取消、Cookie管理、文件上传下载、超时、自定义适配器。

1.依赖导入

dependencies:
  dio: ^3.0.9

2.代码书写

  ///获取首页列表数据,future
  getHomeArticleListDdata(int _page) async {
    try {
      Response response =
          await dio.get(Apis.HOME_ARTICLE_LIST + "/$_page/json");
      var statusCode = response.statusCode;
      if (statusCode == 200) {
        return response;
      } else {
        throw Exception('网络异常:' + response.statusMessage);
      }
    } catch (e) {
      print(e);
    }
  }

调用这个方法

  void getHomeListData() async {
    await ApiService().getHomeArticleListDdata(_page).then((value) {
      //解码得到数据
      var data = json.decode(value.toString());
      setState(() {
        _articleModel = ArticleModel.fromJson(data);
      });
    });
  }

4.json to Dart json数据转换成bean

https://www.devio.org/io/tools/json-to-dart/
在网页内输入json内容,转换成bean内容,复制,修改类名。

你可能感兴趣的:(Flutter)