Dart: http库

本文详细介绍了使用Dart进行网络请求的基本方法,包括如何获取数据、处理服务器错误、中断请求以及上传文件。通过实例展示了http包的使用,如GET请求、错误处理、超时中断和multipart/form-data类型的POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最基本的获取数据

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' }

转载于:https://www.cnblogs.com/ajanuw/p/10999826.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值