1. 添加依赖:
在你的pubspec.yaml文件中添加http包的依赖:
dependencies:
http: ^0.14.0
运行 flutter pub get 命令以获取新的依赖项。
2. 发起HTTP GET 请求:
import 'package:http/http.dart' as http;
void fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
print('Response data: ${response.body}');
} else {
print('Failed to load data. Status code: ${response.statusCode}');
}
}
3. 发起HTTP POST 请求:
import 'package:http/http.dart' as http;
void postData() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
body: {'title': 'foo', 'body': 'bar', 'userId': '1'},
);
if (response.statusCode == 201) {
print('Post successful. Response data: ${response.body}');
} else {
print('Failed to post data. Status code: ${response.statusCode}');
}
}
4. 使用Dart的dart:io库处理文件上传:
import 'dart:io';
import 'package:http/http.dart' as http;
void uploadFile() async {
var request = http.MultipartRequest(
'POST',
Uri.parse('https://example.com/upload'),
);
// 添加文件
var file = await http.MultipartFile.fromPath('file', 'path/to/your/file.txt');
request.files.add(file);
// 添加其他字段
request.fields['field'] = 'value';
// 发送请求
var response = await request.send();
if (response.statusCode == 200) {
print('File uploaded successfully. Response data: ${await response.stream.bytesToString()}');
} else {
print('Failed to upload file. Status code: ${response.statusCode}');
}
}
这只是一些基本的HTTP请求的例子。你可以根据实际需求使用不同的HTTP方法、请求头、请求体等选项。请注意,在实际应用中,你可能需要处理异步操作、异常和其他网络相关的问题。
转载请注明出处:http://www.zyzy.cn/article/detail/9608/Flutter