首页 > 解决方案 > 如何使 Flutter HTTP 部分(范围)请求?

问题描述

代码

我有这个main.dart颤振代码:

import 'package:http/http.dart' as $http;

Future main() async {
  await hit();
}

Future hit() async {
  const url = 'https://data.wikibulary.com/data/plain/index/en/0.bin';
  const len = 10000024;
  final resp = await $http.get(url, headers: {
    'range': 'bytes = ${len - 1}-${len - 1}',
    'cache-control': 'no-cache',
  });
  final headers = resp.headers.entries.fold('', (r, i) => '$r\n${i.key}: ${i.value}');
  print('length: ${resp.bodyBytes.length}\n-------------\nheaders:\n$headers');
}

问题

Windows 桌面和 Android 将忽略范围请求标头。对于 Flutter Web,它工作得很好。

所有三个平台的响应标头:

网站:
statusCode: 206
length: 1
-----------
cache-control: public, max-age=86400000
content-length: 1
content-type: application/octet-stream
date: Sat, 09 Jan 2021 11:12:22 GMT
etag: 0x8D8B4749CC587E6
last-modified: Sat, 09 Jan 2021 08:00:21 GMT
视窗:
statusCode: 200
length: 10000024
-----------
connection: keep-alive
last-modified: Sat, 09 Jan 2021 08:00:21 GMT
cache-control: public, max-age=86400000
access-control-allow-origin: *
date: Sat, 09 Jan 2021 11:09:00 GMT
vary: Accept-Encoding
age: 6367
content-type: application/octet-stream
accept-ranges: bytes
content-length: 10000024
etag: 0x8D8B4749CC587E6
安卓模拟器:
I/flutter ( 5528): statusCode: 200
I/flutter ( 5528): length: 10000024
I/flutter ( 5528): -----------
I/flutter ( 5528):
I/flutter ( 5528): connection: keep-alive
I/flutter ( 5528): last-modified: Sat, 09 Jan 2021 08:00:21 GMT
I/flutter ( 5528): cache-control: public, max-age=86400000
I/flutter ( 5528): access-control-allow-origin: *
I/flutter ( 5528): date: Sat, 09 Jan 2021 11:10:42 GMT
I/flutter ( 5528): vary: Accept-Encoding

标签: flutterdart

解决方案


问题解决了,空间字符在'bytes = ${len - 1}-${len - 1}'

正确的代码是:

final resp = await $http.get(url, headers: {
  'range': 'bytes=${len - 1}-${len - 1}',
  'cache-control': 'no-cache',
});

推荐阅读