send method

  1. @override
Future<Response> send(
  1. Request request
)
override

Sends the request and returns the Response

Implementation

@override
Future<Response> send(Request request) async {
  final method = request.method;
  if (request.body != null && !methodSupportsBody(method)) {
    throw Exception('Sending body is not supported by requested method.');
  }
  final args = <String?>[];
  if (request.followRedirects == null || request.followRedirects!) {
    args.add('-L');
  }
  if (request.maxRedirects != null) {
    args.add('--max-redirs');
    args.add(request.maxRedirects.toString());
  }
  if (userAgent != null) args.addAll(['-A', userAgent]);

  if (socksHostPort != null) {
    switch (socksProxyType) {
      case CurlSocksProxyType.socks4:
        args.add('--socks4');
        break;
      case CurlSocksProxyType.socks4a:
        args.add('--socks4a');
        break;
      case CurlSocksProxyType.socks5:
        args.add('--socks5');
        break;
      case CurlSocksProxyType.socks5hostname:
        args.add('--socks5-hostname');
        break;
    }
    args.add(socksHostPort);
  }
  args.addAll(['-X', method.toUpperCase()]);

  request.headers.toSimpleMap().forEach((key, value) {
    args.addAll(['-H', '$key:$value']);
  });

  // --data parameter added in GET and POST Method. If method is 'GET', body may no have any effect in the request. UTF-8 encoding setted as default.
  if (request.body != null) {
    if (request.body is! List<int>) {
      throw Exception('Request body type must be List<int>');
    }
    args.addAll(['--data', utf8.decode(request.body)]);
  }
  args.add(request.uri.toString());
  // TODO: handle status code and reason phrase
  var prf = Process.run(executable ?? 'curl',
      args.where((element) => element != null).map((e) => e!).toList(),
      stdoutEncoding: null);
  if (request.timeout != null && request.timeout! > Duration.zero) {
    prf = prf.timeout(request.timeout!);
  }
  final pr = await prf;
  final list = (pr.stdout as List).cast<int>();
  return Response(pr.exitCode == 0 ? 200 : -1, '', Headers(),
      Stream.fromIterable(<List<int>>[list]));
}