首页 > Web开发 > 详细

Drart: 使用http库获取服务器数据

时间:2019-06-10 20:29:28      阅读:170      评论:0      收藏:0      [点我收藏+]

最基本的获取数据

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

Drart: 使用http库获取服务器数据

原文:https://www.cnblogs.com/ajanuw/p/10999826.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!