

dependencies:
flutter:
sdk: flutter
http: ^0.13.4 # 请检查并使用最新版本

import 'package:http/http.dart' as http;
import 'package:http/http.dart' as http;
void main() {
_doGet();
}
//请求成功
_success(response) {
var result = response.body;
print("请求成功: $result");
}
//请求失败
_failed(response) {
var errorCode = response.statusCode;
var errorMessage = response.body;
print("请求失败:errorCode: $errorCode errorMessage: $errorMessage");
}
//请求成功码
const int SUCCESS_CODE = 200;
//请求 URL
const String GET_URL =
'https://api.geekailab.com/uapi/test/test?requestPrams=11';
//Get 请求
_doGet() async {
var url = Uri.parse(GET_URL);
var response = await http.get(url);
if (response.statusCode == SUCCESS_CODE) {
//成功
_success(response);
} else {
//失败
_failed(response);
}
}
使用 post 发送数据常用的内容类型主要有两种:
import 'package:http/http.dart' as http;
void main() {
_postFormData();
}
//请求成功
_success(response) {
var result = response.body;
print("请求成功: $result");
}
//请求失败
_failed(response) {
var errorCode = response.statusCode;
var errorMessage = response.body;
print("请求失败:errorCode: $errorCode errorMessage: $errorMessage");
}
//请求成功码
const int SUCCESS_CODE = 200;
// post form 请求地址
const String POST_FORM_URL = 'https://api.geekailab.com/uapi/test/test';
// post 请求
_postFormData() async {
var url = Uri.parse(POST_FORM_URL);
//请求参数Map
var params = {'name': 'leon', 'age': '18'};
var response = await http.post(url,
body: params); //默认为x-www-form-urlencoded 格式,所以可以不用设置content-type
// var response = await http.post(url, body: params, headers: {
// 'content-type': 'x-www-form-urlencoded'
// });
if (response.statusCode == SUCCESS_CODE) {
//成功
_success(response);
} else {
//失败
_failed(response);
}
}
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
_postJsonData();
}
//请求成功
_success(response) {
var result = response.body;
print("请求成功: $result");
}
//请求失败
_failed(response) {
var errorCode = response.statusCode;
var errorMessage = response.body;
print("请求失败:errorCode: $errorCode errorMessage: $errorMessage");
}
//请求成功码
const int SUCCESS_CODE = 200;
// post json 请求地址
const String POST_JSON_URL = 'https://api.geekailab.com/uapi/test/testJson';
// post 请求
_postJsonData() async {
var url = Uri.parse(POST_JSON_URL);
//请求参数 json 类型
var params = {'name': 'leon', 'age': '18'};
var json = jsonEncode(params);
var response = await http.post(url, body: json, headers: {
'content-type': 'application/json'
}); //设置content-type为application/json
if (response.statusCode == SUCCESS_CODE) {
//成功
_success(response);
} else {
//失败
_failed(response);
}
}
示例:将 json string 转换成 map
var jsonString = response.body;
var map = jsonDecode(jsonString);
var result = map['message'];