net.dart 856 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import '../globals.dart';

/// Download a file from the given URL and return the bytes.
Future<List<int>> fetchUrl(Uri url) async {
  printTrace('Downloading $url.');

  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.getUrl(url);
  HttpClientResponse response = await request.close();

  printTrace('Received response statusCode=${response.statusCode}');
  if (response.statusCode != 200)
    throw new Exception(response.reasonPhrase);

  BytesBuilder responseBody = new BytesBuilder(copy: false);
  await for (List<int> chunk in response)
    responseBody.add(chunk);

  return responseBody.takeBytes();
}