Line data Source code
1 : // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 : // for details. All rights reserved. Use of this source code is governed by a
3 : // BSD-style license that can be found in the LICENSE file.
4 :
5 : import 'dart:async';
6 : import 'dart:io';
7 :
8 : import 'package:async/async.dart';
9 :
10 : import 'base_client.dart';
11 : import 'base_request.dart';
12 : import 'exception.dart';
13 : import 'streamed_response.dart';
14 :
15 : /// A `dart:io`-based HTTP client.
16 : ///
17 : /// This is the default client when running on the command line.
18 : class IOClient extends BaseClient {
19 : /// The underlying `dart:io` HTTP client.
20 : HttpClient _inner;
21 :
22 : /// Creates a new HTTP client.
23 0 : IOClient([HttpClient inner]) : _inner = inner ?? new HttpClient();
24 :
25 : /// Sends an HTTP request and asynchronously returns the response.
26 : Future<StreamedResponse> send(BaseRequest request) async {
27 0 : var stream = request.finalize();
28 :
29 : try {
30 0 : var ioRequest = await _inner.openUrl(request.method, request.url);
31 :
32 : ioRequest
33 0 : ..followRedirects = request.followRedirects
34 0 : ..maxRedirects = request.maxRedirects
35 0 : ..contentLength = request.contentLength == null
36 : ? -1
37 0 : : request.contentLength
38 0 : ..persistentConnection = request.persistentConnection;
39 0 : request.headers.forEach((name, value) {
40 0 : ioRequest.headers.set(name, value);
41 : });
42 :
43 0 : var response = await stream.pipe(
44 0 : DelegatingStreamConsumer.typed(ioRequest));
45 0 : var headers = <String, String>{};
46 0 : response.headers.forEach((key, values) {
47 0 : headers[key] = values.join(',');
48 : });
49 :
50 0 : return new StreamedResponse(
51 0 : DelegatingStream.typed<List<int>>(response).handleError((error) =>
52 0 : throw new ClientException(error.message, error.uri),
53 0 : test: (error) => error is HttpException),
54 0 : response.statusCode,
55 0 : contentLength: response.contentLength == -1
56 : ? null
57 0 : : response.contentLength,
58 : request: request,
59 : headers: headers,
60 0 : isRedirect: response.isRedirect,
61 0 : persistentConnection: response.persistentConnection,
62 0 : reasonPhrase: response.reasonPhrase);
63 0 : } on HttpException catch (error) {
64 0 : throw new ClientException(error.message, error.uri);
65 : }
66 0 : }
67 :
68 : /// Closes the client. This terminates all active connections. If a client
69 : /// remains unclosed, the Dart process may not terminate.
70 : void close() {
71 0 : if (_inner != null) _inner.close(force: true);
72 0 : _inner = null;
73 : }
74 : }
|