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