最基本的获取数据

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
}

服务器抛出错误

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
}

抓取请求错误

try {
var r = await http.get('http://closeExample.com');
print(r.statusCode);
} on SocketException catch (e) {
print(e); // SocketException: Failed host lookup: 'closeexample.com' (OS Error: No address associated with hostname, errno = 7)
}

在指定的时间中断请求

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

获取文件下载进度

使用send方法发送,可以返回一个监听流

import 'dart:io';
import 'dart:typed_data'; import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; Uint8List image;
ImageChunkEvent loadingProgress;
ImageNetworkError error;
var _client = http.Client(); /// request
http.Request get _req {
var req = http.Request(
'get',
Uri.parse(widget.src),
);
if (widget.headers != null) {
for (MapEntry<String, String> m in widget.headers.entries) {
req.headers[m.key] = m.value;
}
}
return req;
} @override
void initState() {
super.initState();
_init();
} Future<void> _init() async {
http.StreamedResponse r = await _client.send(_req);
print(r.statusCode);
List<int> ds = [];
r.stream.listen(
(List<int> d) {
ds.addAll(d);
setState(() {
loadingProgress = ImageChunkEvent(
cumulativeBytesLoaded: ds.length, // 当前加载
expectedTotalBytes: r.contentLength, // 总长度
);
});
},
onDone: () {
setState(() {
image = Uint8List.fromList(ds);
loadingProgress = null;
});
_client?.close();
},
);
} @override
void dispose() {
_client?.close();
super.dispose();
} @override
Widget build(BuildContext context) {
if (loadingProgress == null &&
image == null &&
widget.loadingWidget != null) {
return _loadingWidget();
}
if (widget.loadingBuilder != null) {
return _loadingBuilder();
} else {
return Image.memory(image);
}
}
}

创建自己的request

import 'dart:convert';
import 'dart:io'; import 'package:flutter/material.dart';
import 'package:http/http.dart' as http; final SkyClient skyClient = SkyClient(http.Client());
void main() => runApp(MyApp()); class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
} class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
} class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('home page'),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.send),
onPressed: () async {
try {
var r = await skyClient.getFirstUser('januwA');
print(r);
} on SocketException catch (e) {
print(e);
}
},
),
);
}
} class SkyClient extends http.BaseClient {
final http.Client _inner; SkyClient(this._inner); @override
Future<http.StreamedResponse> send(http.BaseRequest request) {
return _inner.send(request);
} @override
Future<http.Response> get(url, {Map<String, String> headers}) {
return _inner.get(url, headers: headers);
} Future<Map<String, dynamic>> getFirstUser(String name,
{Map<String, String> headers}) async {
var r = await _inner.get("https://api.github.com/search/users?q=$name",
headers: headers);
return jsonDecode(r.body)['items'][0];
}
}

上传文件获取上传进度

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:http/http.dart' as http; final String __filename = Platform.script.path.replaceFirst('/', '');
final String __dirname = path.dirname(__filename);
final Uri uri = Uri.parse("http://localhost:3000/upload");
final String imgPath = path.join(__dirname, 'test.jpg');
main() async {
final request = await HttpClient().postUrl(uri);
int byteCount = 0; var requestMultipart = http.MultipartRequest("POST", uri)
..files.addAll([
await http.MultipartFile.fromPath("file", imgPath),
])
..fields.addEntries([
MapEntry("name", "ajanuw"),
]); request.contentLength = requestMultipart.contentLength; var msStream = requestMultipart.finalize();
requestMultipart.headers.forEach((k, v) => request.headers.set(k, v)); await request.addStream(msStream.transform(
StreamTransformer.fromHandlers(
handleData: (data, sink) {
sink.add(data);
byteCount += data.length;
print(
"${((byteCount / requestMultipart.contentLength) * 100).toInt()}/${100}");
},
handleError: (error, stack, sink) => print('upload error'),
handleDone: (sink) => sink.close(),
),
)); final httpResponse = await request.close();
print(httpResponse.statusCode); var contents = StringBuffer();
httpResponse.transform(utf8.decoder).listen(
(String data) => contents.write(data),
onDone: () {
print(contents.toString());
},
);
}

run

> dart .\bin\main.dart
0/100
0/100
80/100
99/100
99/100
100/100
201
upload sucess

serevr

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
UploadedFile(@UploadedFile() file) {
console.log(file);
return "upload sucess";
}

上传文件获取上传进度(2)

import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:http/http.dart' as http; final String __filename = Platform.script.path.replaceFirst('/', '');
final String __dirname = path.dirname(__filename);
final Uri uri = Uri.parse("http://localhost:3000/upload");
final String imgPath = path.join(__dirname, 'test.jpg'); class MultipartRequest extends http.MultipartRequest {
Function(int bytes, int total) onProgress;
MultipartRequest(String method, Uri url, {this.onProgress})
: super(method, url); /// 重写这个方法
@override
http.ByteStream finalize() {
final byteStream = super.finalize();
if (onProgress == null) return byteStream;
final total = this.contentLength;
int bytes = 0; final t = StreamTransformer.fromHandlers(
handleData: (List<int> data, EventSink<List<int>> sink) {
bytes += data.length;
onProgress(bytes, total);
sink.add(data);
},
);
final stream = byteStream.transform(t);
return http.ByteStream(stream);
}
} main() async {
var uri = Uri.parse("http://localhost:3000/upload"); http.MultipartRequest request = MultipartRequest(
"POST",
uri,
onProgress: (int bytes, int total) {
print("${((bytes / total) * 100).toInt()}/${100}");
},
);
request.files.add(
await http.MultipartFile.fromPath('file', path.join(__dirname, 'test.jpg')),
);
var r = await request.send();
print(r.statusCode);
print(await r.stream.bytesToString());
}

Dart http库的更多相关文章

  1. Dart自定义库、系统库和第三方库

    /* 前面介绍Dart基础知识的时候基本上都是在一个文件里面编写Dart代码的,但实际开发中不可能这么写,模块化很重要,所以这就需要使用到库的概念. 在Dart中,库的使用时通过import关键字引入 ...

  2. Dart: path库

    path库pub地址 安装: dependencies: path: 使用: import 'dart:io'; import 'package:path/path.dart' as path; ma ...

  3. flutter-web利用dart js 库发起http request

    初学flutter,初学前端,尝试在dart中直接使用HttpClient时,直接报出Platform not supported,查资料发现他还不支持浏览器. 通过查阅资料发现可以借助axios 与 ...

  4. Dart: puppeteer库

    和node的差不多,只有写API不一样 puppeteer 地址 安装依赖 dependencies: puppeteer: ^1.7.1 下载 chrome-win 到 <project_ro ...

  5. Angular JS | Closure | Google Web Toolkit | Dart | Polymer 概要汇集

    AngularJS | Closure | Google Web Toolkit | Dart | Polymer GWT https://code.google.com/p/google-web-t ...

  6. [dart学习]第三篇:dart变量介绍 (二)

    本篇继续介绍dart变量类型,可参考前文:第二篇:dart变量介绍 (一) (一)final和const类型 如果你不打算修改一个变量的值,那么就把它定义为final或const类型.其中:final ...

  7. 9.Libraries and visibility 库和可见性

    import和liabrary指令可以帮助你创建模块化,可复用的代码.库不仅仅提供API,也是一个私有化单元:库中已下划线(_)开头的类都是对外不可访问的.每个Dart的应用也是一个包,尽管它没有使用 ...

  8. [Dart]语法基础

    此页面向您展示如何使用每个主要Dart功能,从变量和运算符到类和库,假设您已经知道如何使用其他语言编程. 要了解有关Dart核心库的更多信息,请参阅 Dart Libraries之旅.无论何时需要有关 ...

  9. 2.Built-in types-基本数据类型(Dart中文文档)

    初次翻译,部分内容并非按字面翻译,是按本人理解进行了内容重组.如有错误望指正. Dart语言内置如下数据类型: numbers strings booleans lists (所谓的数组) maps ...

随机推荐

  1. Spring听课笔记(tg)AOP

    好文:https://blog.csdn.net/javazejian/article/details/56267036 通过一个实例来理解 1.  需求:实现算术计算器,可以加减乘除,同时记录日志 ...

  2. 反向传播(Back Propagation)

    反向传播(Back Propagation) 通常在设计好一个神经网络后,参数的数量可能会达到百万级别.而我们利用梯度下降去跟新参数的过程如(1).但是在计算百万级别的参数时,需要一种有效计算梯度的方 ...

  3. Springboot 项目部署到服务器上

    项目部署到服务器上,有两种方式,一种 jar 包,一种 war 包 jar包 部署时,后续的域名配置,SSL证书等在nginx中配置 war包 部署时,后续的域名配置可以在tomcat中配置就好,修改 ...

  4. 数据中心网络技术新贵:VXLAN与园区网络虚拟化

    摘要:为了应对传统数据中心网络对服务器虚拟化技术的限制,VXLAN技术应运而生. 1 概述 传统数据中心网络面临的问题 虚拟机规模受设备表项规格限制 在传统二层网络中,交换机通过查询MAC地址表来转发 ...

  5. idea--忽略隐藏文件、文件夹的设置操作

    文章由来 公司同事在群里问了个问题,如下: 为了大家看清,将图特意贴出来: 这人还删除idae重装了下,哈哈,才到群里问的. 解决思路(按顺序) 1.我让他直接拉会,共享桌面我给看了下,首先是open ...

  6. shell脚本的使用该熟练起来了,你说呢?(篇二)

    继续前一篇的文章: shell脚本的使用该熟练起来了,你说呢?(篇一) 作者:良知犹存 转载授权以及围观:欢迎添加微信公众号:羽林君 shell传递参数 shell传递参数 我们可以在执行 Shell ...

  7. 零基础如何使用python处理字符串?

    摘要:Python的普遍使用场景是自动化测试.爬取网页数据.科学分析之类,这其中都涉及到了对数据的处理,而数据的表现形式很多,今天我们来讲讲字符串的操作.   字符串是作为任意一门编程语言的基础,在P ...

  8. EXCEL序列

  9. Codeforces Round #575 (Div. 3) E. Connected Component on a Chessboard

    传送门 题意: 给你一个黑白相间的1e9*1e9的棋盘,你需要从里面找出来由b个黑色的格子和w个白色的格子组成的连通器(就是你找出来的b+w个格子要连接在一起,不需要成环).问你可不可以找出来,如果可 ...

  10. ef学习记录

    EF Core (EntityFramework Core)是实体关系映射(O/RM)数据库访问框架.这个模式的好处就是让开发人员可以用对象模型来操作数据库,这是一种对开发人员较为友好的方式. O/R ...