最基本的获取数据
import 'package:http/http.dart' as http;
main(List<String> args) async {
var url = Uri.http('localhost:5000', '/test');
var r = await http.get(url);
print(r.body); // hello world
print(r.statusCode); // 服务器返回的状态码200
}
@Get('test')
getHello(): string {
return 'hello wolrd';
}
服务器抛出错误
import 'package:http/http.dart' as http;
main(List<String> args) async {
var url = Uri.http('localhost:5000', '/test');
var r = await http.get(url);
print(r.body); // {"statusCode":500,"error":"Internal Server Error","message":"服务器错误"}
print(r.statusCode); // 500
}
@Get('test')
getHello(): string {
throw new InternalServerErrorException('服务器错误');
return 'hello wolrd';
}
在指定的时间中断请求
import 'package:http/http.dart' as http;
main(List<String> args) async {
var client = http.Client();
Future.delayed(Duration(seconds: 5)).then((_) {
print('关闭这个请求');
client.close();
});
try {
var url = Uri.http('localhost:5000', '/test');
print('请求开始');
var r = await client.get(url);
print(r.body);
print(r.statusCode);
} on http.ClientException catch(e) {
/// 捕获中断后抛出的错误
print(e);
} catch (e) {
print('Other Error: $e');
}
}
@Get('test')
async getHello(): Promise<string> {
//延迟 10s后发出数据
return await new Promise(res => {
setTimeout(() => {
res('hello world');
}, 10000);
});
}
打印结果
$ dart ./bin/main.dart
请求开始
关闭这个请求
Connection closed before full header was received
发送文件到服务器
客服端:
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:http/http.dart';
String __filename = Platform.script.path.replaceFirst('/', '');
String __dirname = path.dirname(__filename);
main(List<String> arguments) async {
var uri = Uri.parse("http://localhost:3000/upload");
MultipartRequest request = MultipartRequest("POST", uri);
request.fields['user'] = 'Ajanuw';
request.files.add(
await MultipartFile.fromPath('file', path.join(__dirname, 'test.jpg')),
);
var r = await request.send();
print(r.statusCode);
print(await r.stream.bytesToString());
}
服务器端代码片段:
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
UploadedFile(@UploadedFile() file, @Body() body) {
console.log(file);
console.log(body);
const writeImage = createWriteStream(
join(__dirname, '..', 'upload', `${file.originalname}`),
);
writeImage.write(file.buffer);
return 'ok';
}
执行客服端代码:
λ dart ./bin/main.dart
201
ok
服务端打印:
[0] { fieldname: 'file',
[0] originalname: 'test.jpg',
[0] encoding: '7bit',
[0] mimetype: 'application/octet-stream',
[0] buffer:
[0] <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff fe 00 3b 43 52 45 41 54 4f 52 3a 20 67 64 2d 6a 70 65 67 20 76 31 2e 30 20 28 75 73 69 ... >,
[0] size: 341398 }
[0] [Object: null prototype] { user: 'Ajanuw' }