• Flutter学习9 - http 中 get/post 请求示例


    1、配置 http

    pubspec.yaml

    dependencies:
      http:  ^0.13.4
      flutter:
        sdk: flutter
    
    • 1
    • 2
    • 3
    • 4

    .dart

    import 'package:http/http.dart' as http;
    
    • 1

    2、示例

    (1)工具使用 - postman

    • 可以使用 postman 插件中的示例来测试 get/post 请求

    在这里插入图片描述

    (2)代码实现示例

    • 点击按钮,发起 Get/Post 请求,并将请求结果展示到界面上

    在这里插入图片描述

    http_page.dart

    
    
    • 1

    main.dart

    
    
    • 1

    (3)get 请求补充

    在这里插入图片描述

    • 通过以上示例可知,get 请求的 url 为:https://cx.shouji.360.cn/phonearea.php?number=17688888888
    • 因为返回结果的汉字用了 utf8 编码,所以需要对结果进行 utf8 解码

    发起请求

      //发送 Get 请求
      _doGet() async {
        var url =
            Uri.parse('https://cx.shouji.360.cn/phonearea.php?number=17688888888');
        var response = await http.get(url);
        if (response.statusCode == 200) {
          //请求成功
          _success(response);
        } else {
          //请求失败
          _failed(response);
        }
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    处理请求结果

      //请求成功
      _success(http.Response response) {
        setState(() {
          resultShow = '请求成功:${_decodeUtf8(response.body)}';
        });
      }
    
      //请求失败
      _failed(http.Response response) {
        setState(() {
          resultShow =
              "请求失败:errorCode: ${response.statusCode}   errorMessage: ${response.body}";
        });
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    uf8 解码

      // utf8 解码
      _decodeUtf8(String responseBody) {
        var bytes = Uint8List.fromList(responseBody.codeUnits);
        String decodeString = utf8.decode(bytes);
        var decodeMap = json.decode(decodeString);
        return decodeMap;
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    (4)post 请求补充 - form

    在这里插入图片描述

    • url:http://api.crap.cn/visitor/example/post.do
    • form:{ ‘param’: ‘测试22’, ‘email’: ‘crap.cn@gmail.com’, ‘555’: ‘我’ }

    发起请求

      //发送 Post 请求 - form
      _doFormPost() async {
        var url = Uri.parse('http://api.crap.cn/visitor/example/post.do');
        var params = {
          'param': '测试22',
          'email': 'crap.cn@gmail.com',
          '555': '我'
        }; //如果传 Map 类型,必须是 Map,否则会解析报错
        var response =
            await http.post(url, body: params); //默认是 form 类型,所以无需设置 content - type
        if (response.statusCode == 200) {
          //请求成功
          _success(response);
        } else {
          //请求失败
          _failed(response);
        }
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    处理请求结果

      //请求成功
      _success(http.Response response) {
        setState(() {
          //返回结果的汉字用了 utf8 编码,所以需要对结果进行 utf8 解码
          // resultShow = '请求成功:${_decodeUtf8(response.body)}';
    
          //返回结果的汉字未用 utf8 编码,所以无需解码
          resultShow = '请求成功:${response.body}';
        });
      }
    
      //请求失败
      _failed(http.Response response) {
        setState(() {
          resultShow =
              "请求失败:errorCode: ${response.statusCode}   errorMessage: ${response.body}";
        });
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 返回结果的汉字未用 utf8 编码,所以无需解码

    (5)post 请求补充 - json

    在这里插入图片描述

    • url:http://api.crap.cn/visitor/example/json.do
    • json:{ “id”:“8989-dddvdg”, “name”:“文章标题-JSON格式参数演示”, “brief”:“快速入门json参数”, “category”:“分类” }

    发起请求

      //发送 Post 请求 - json
      _doJsonPost() async {
        var url = Uri.parse('http://api.crap.cn/visitor/example/json.do');
        var params = {
          "id": "8989-dddvdg",
          "name": "文章标题-JSON格式参数演示",
          "brief": "快速入门json参数",
          "category": "分类"
        };
        var json = jsonEncode(params);
        var response = await http.post(url, body: json, headers: {
          'content-type': 'application/json'
        }); //设置content-type为application/json
        if (response.statusCode == 200) {
          //请求成功
          _success(response);
        } else {
          //请求失败
          _failed(response);
        }
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    处理请求结果

      //请求成功
      _success(http.Response response) {
        setState(() {
          //返回结果的汉字用了 utf8 编码,所以需要对结果进行 utf8 解码
          // resultShow = '请求成功:${_decodeUtf8(response.body)}';
    
          //返回结果的汉字未用 utf8 编码,所以无需解码
          resultShow = '请求成功:${response.body}';
        });
      }
    
      //请求失败
      _failed(http.Response response) {
        setState(() {
          resultShow =
              "请求失败:errorCode: ${response.statusCode}   errorMessage: ${response.body}";
        });
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3、补充

    • 快捷键 stf 创建有状态 widget
    //输入字母 stf
    class  extends StatefulWidget {
      const ({super.key});
    
      
      State<> createState() => _State();
    }
    
    class _State extends State<> {
      
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 给类命名,并导入包
    import 'package:flutter/cupertino.dart';
    
    class HttpGetDemo  extends StatefulWidget {
      const HttpGetDemo({super.key});
    
      
      State<HttpGetDemo> createState() => _State();
    }
    
    class _State extends State<HttpGetDemo> {
      
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    【接口测试】Jmeter接口实战-Dubbo接口+造10W数据测试(详细)
    HashMap<String,Object>是什么?什么情况下使用HashMap?
    利用pytorch自定义CNN网络(三):构建CNN模型
    React源码分析8-状态更新的优先级机制
    深度学习03——手写数字识别实例
    vue3-新特性
    python 容器之列表(list)练习
    SpringBoot 接口数据加解密
    Hadoop运维工具箱之HDFS集群扩容与缩容-尚硅谷大数据培训
    单相过压继电器DVR-G-100-1 0~500V AC/DC220V 导轨安装
  • 原文地址:https://blog.csdn.net/weixin_41733225/article/details/136460794