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

news2024/10/5 18:32:39

1、配置 http

pubspec.yaml

dependencies:
  http:  ^0.13.4
  flutter:
    sdk: flutter
  • http 库最新插件版本查看:https://pub.dev/packages/http
  • 不一定要用最新版本 http,要使用项目所能支持的版本

.dart

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

2、示例

(1)工具使用 - postman

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

在这里插入图片描述

(2)代码实现示例

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

在这里插入图片描述

http_page.dart

import 'dart:convert';
import 'dart:typed_data';

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

class HttpDemo extends StatefulWidget {
  const HttpDemo({super.key});

  
  State<HttpDemo> createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  //展示请求结果
  var resultShow = "";

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Http 的 post 请求"),
      ),
      body: Column(
        children: [
          Center(
            child: _httpGetButton(),
          ),
          //post 请求按钮 - form
          Center(
            child: _httpPostFormButton(),
          ),
          //post 请求按钮 - json
          Center(
            child: _httpPostJsonButton(),
          ),
          Row(
            children: [
              Expanded(
                  child: Text(
                '请求结果:\n $resultShow',
                textAlign: TextAlign.left,
              )),
            ],
          ),
        ],
      ),
    );
  }

  //get 按钮
  _httpGetButton() {
    return ElevatedButton(onPressed: _doGet, child: const Text('发起 Get 请求'));
  }

  //post 按钮 - form
  _httpPostFormButton() {
    return ElevatedButton(
        onPressed: _doFormPost, child: const Text('发起 post 请求 - form'));
  }

  //post 按钮 - json
  _httpPostJsonButton() {
    return ElevatedButton(
        onPressed: _doJsonPost, child: const Text('发起 post 请求 - json'));
  }

  // utf8 解码
  _decodeUtf8(String responseBody) {
    var bytes = Uint8List.fromList(responseBody.codeUnits);
    String decodeString = utf8.decode(bytes);
    var decodeMap = json.decode(decodeString);
    return decodeMap;
  }

  //请求成功
  _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}";
    });
  }

  //发送 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);
    }
  }

  //发送 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<String, String>,否则会解析报错
    var response =
        await http.post(url, body: params); //默认是 form 类型,所以无需设置 content - type
    if (response.statusCode == 200) {
      //请求成功
      _success(response);
    } else {
      //请求失败
      _failed(response);
    }
  }

  //发送 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);
    }
  }
}

main.dart

import 'package:flutter/material.dart';

import 'http_page.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Leon Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HttpDemo(),
    );
  }
}

(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);
    }
  }

处理请求结果

  //请求成功
  _success(http.Response response) {
    setState(() {
      resultShow = '请求成功:${_decodeUtf8(response.body)}';
    });
  }

  //请求失败
  _failed(http.Response response) {
    setState(() {
      resultShow =
          "请求失败:errorCode: ${response.statusCode}   errorMessage: ${response.body}";
    });
  }

uf8 解码

  // utf8 解码
  _decodeUtf8(String responseBody) {
    var bytes = Uint8List.fromList(responseBody.codeUnits);
    String decodeString = utf8.decode(bytes);
    var decodeMap = json.decode(decodeString);
    return decodeMap;
  }

(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<String, String>,否则会解析报错
    var response =
        await http.post(url, body: params); //默认是 form 类型,所以无需设置 content - type
    if (response.statusCode == 200) {
      //请求成功
      _success(response);
    } else {
      //请求失败
      _failed(response);
    }
  }

处理请求结果

  //请求成功
  _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}";
    });
  }
  • 返回结果的汉字未用 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);
    }
  }

处理请求结果

  //请求成功
  _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}";
    });
  }

3、补充

  • 快捷键 stf 创建有状态 widget
//输入字母 stf
class  extends StatefulWidget {
  const ({super.key});

  
  State<> createState() => _State();
}

class _State extends State<> {
  
  Widget build(BuildContext context) {
    return const Placeholder();
  }
}
  • 给类命名,并导入包
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();
  }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1500072.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于UDP实现直播间聊天的功能

需求&#xff1a;软件划分为用户客户端和主播服务端两个软件client.c和server.c 用户客户端负责&#xff1a;1.接收用户的昵称2.接收用户输入的信息&#xff0c;能够将信息发送给服务端3.接收服务端回复的数据信息,并完成显示主播服务端负责&#xff1a;1.对所有加入直播间的用…

基于uniapp cli项目开发的老项目,运行报错path.replace is not a function

项目&#xff1a;基于uniapp cli的微信小程序老项目 问题&#xff1a;git拉取代码&#xff0c;npm安装包时就报错&#xff1b; cnpm能安装成功包&#xff0c;运行报错 三种方法尝试解决&#xff1a; 更改代码&#xff0c;typeof pathstring的话&#xff0c;才走path.replace…

mysql的语法总结2

命令&#xff1a; mysql -u 用户名 -p mysql登录 命令&#xff1a;create database u1 创建数据库u1 查询数据库 使用数据库u1 创建表department 查询表department ALTER TABLE 表名 操作类型&#xff1b; 操作类型可以有以下的操作&#xff1a; 添加列&#x…

【算法 高级数据结构】树状数组:一种高效的数据结构(一)

&#x1f680;个人主页&#xff1a;为梦而生~ 关注我一起学习吧&#xff01; &#x1f4a1;专栏&#xff1a;算法题、 基础算法~赶紧来学算法吧 &#x1f4a1;往期推荐&#xff1a; 【算法基础 & 数学】快速幂求逆元&#xff08;逆元、扩展欧几里得定理、小费马定理&#x…

Baumer工业相机堡盟工业相机如何通过NEOAPI SDK实现双快门采集两张曝光时间非常短的图像(C#)

Baumer工业相机堡盟工业相机如何通过NEOAPI SDK实现双快门采集两张曝光时间非常短的图像&#xff08;C#&#xff09; Baumer工业相机Baumer工业相机定序器功能的技术背景Baumer工业相机通过NEOAPI SDK使用定序器功能预期的相机动作技术限制定序器的工作原理 Baumer工业相机通过…

20个Python函数程序实例

前面介绍的函数太简单了&#xff1a; 以下是 20 个不同的 Python 函数实例 下面深入一点点&#xff1a; 以下是20个稍微深入一点的&#xff0c;使用Python语言定义并调用函数的示例程序&#xff1a; 20个函数实例 简单函数调用 def greet():print("Hello!")greet…

WPF Border控件 基本使用

Border 基本使用 1单线效果 代码&#xff1a; <Border Grid.Row"0" BorderThickness"0,0,0,1" BorderBrush"Red" /> 说明&#xff1a; BorderThickness"0,0,0,1" 可以分别设置四条边&#xff0c;顺序是&#xff1a;左 上 右…

【微信小程序】基本语法

目录 一、列表渲染&#xff08;包括wx:for改变默认&#xff09; 二、事件冒泡和事件捕获 三、生命周期 一、列表渲染&#xff08;包括wx:for改变默认&#xff09; 1、列表渲染(wx-for、block 改变默认wx:for item等) <view> {{msg}} </view> //渲染跟普通vu…

云计算项目十:ES集群安装|部署kibana

ES集群安装 部署ES集群&#xff0c;用于ELK日志分析平台的构建 es-0001 主机更改 /etc/hosts [rootes-0001 ~]# vim /etc/hosts 192.168.1.71 es-0001 192.168.1.72 es-0002 192.168.1.73 es-0003 192.168.1.74 kibana 192.168.1.75 logstash # 将最新的/etc/hosts配置文件更…

Python绘图-12地理数据可视化

Matplotlib 自 带 4 类别 地理投影&#xff1a; Aitoff, Hammer, Mollweide 及 Lambert 投影&#xff0c;可以 结 合以下四 张 不同 的 图 了解四 种 不同投影 区别 。 12.1Aitoff投影 12.1.1图像呈现 12.1.2绘图代码 import numpy as np # 导入numpy库&#xff0c;用于…

2024年大语言模型的微调

一个LLM的生命周期包含多个步骤&#xff0c;下面将讨论这个周期中最活跃、最密集的部分之一 -- fine-tuning(微调)过程。 LLM的生命周期 下面展示了LLM的生命周期&#xff1a; 愿景和范围&#xff1a;首先需要定义项目的愿景&#xff0c;你想让你的LLM作为一个更加通用的工具…

双体系Java学习之关键字,标识符以及命名规范

刚开学&#xff0c;然后之前的课程暂时停在了多态&#xff0c;接下来开始跟着学校的步伐重新开始学一下&#xff0c;谢谢&#xff01;&#xff01;&#xff01; 之前的课程也会找个时间补起来的&#xff0c;谢谢大家&#xff01; 关键字 标识符 命名规范

STM 32 HAL库 内部FLash读写调试的问题

问题1&#xff1a;STM32G0 系列 256KB内部FLash大小&#xff0c;无法读写 分析&#xff1a;从STM32F103C8 移植过来的Flash操作代码&#xff0c;发现无法进行读写&#xff0c;返回 HAL_ERROR 错误&#xff0c;随后&#xff0c;检查在写之前是否擦除成功&#xff0c;检查代码发…

Oracle VM VirtualBox 安装完Ubuntu系统后一直提示安装Ubuntu

是因为存储设置有问题&#xff0c;把Ubuntu镜像添加进去了,移除后重启虚拟机就不会提示了 以下是配置的移除后的界面。

羊大师揭秘,女性喝羊奶有什么好处

羊大师揭秘&#xff0c;女性喝羊奶有什么好处 女性喝羊奶有多种好处。首先&#xff0c;羊奶富含钙元素&#xff0c;有助于预防女性体内缺钙和老年女性骨质疏松&#xff0c;从而增强骨骼密度。其次&#xff0c;羊奶中的色氨酸和烟酸等成分有助于促进睡眠&#xff0c;改善睡眠质…

NLP_文本张量表示方法_2(代码示例)

目标 了解什么是文本张量表示及其作用.文本张量表示的几种方法及其实现. 1 文本张量表示 将一段文本使用张量进行表示&#xff0c;其中一般将词汇为表示成向量&#xff0c;称作词向量&#xff0c;再由各个词向量按顺序组成矩阵形成文本表示. ["人生", "该&q…

探索安全与灵活性的边界,波卡账户抽象与多签管理的创新之路

相信大家在刚刚进入 web3 的时候都或多或少面临着一个普遍而棘手的问题&#xff0c;私钥的安全管理。私钥一旦丢失或被盗&#xff0c;用户将永久失去对他们加密资产的访问权。此外&#xff0c;随着区块链应用场景的多样化&#xff0c;这种单一模式已经无法满足复杂的交易结构和…

鸿蒙App基础

像素单位 .1、基础单位 为开发者提供4种像素单位&#xff0c;框架采用vp为基准数据单位。 PS&#xff1a;个人建议使用lpx&#xff0c;配置好配置文件&#xff0c;这里就可以按照UI设计稿实际的来&#xff0c;可以更好的实现设计效果 名称描述px屏幕物理像素单位vp屏幕密度相…

Unity 给刚体一个力或速度

创建平面和小球&#xff0c;给力或给速度让其弹起 给小球挂载刚体&#xff08;Rigibdody&#xff09;和脚本 &#xff08;力是累计或者衰减的&#xff0c;直接给速度就是赋值&#xff0c;但如果速度就和力类似了&#xff09; using System.Collections; using System.Collect…

防御保护IPSEC实验

要求&#xff1a;在FW5和FW3之间建立一条IPSEC通道&#xff0c;保证10.0.2.0/24网段可以正常访问到192.168.1.0/24. 因为是双机热备状态则只需要配置FW1主设备。 新建ACL待加密数据流 安全建议&#xff1a; IPSec参数配置 FW3配置如下与FW1类似&#xff1a; FW1中新建安全策略…