Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

REST through SSH Tunnel

See more REST Examples

Demonstrates how to connect through an SSH Tunnel (via port-forwarding) to make REST API calls.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final tunnel = CkSocket();

  final sshHostname = 'sftp.example.com';
  final sshPort = 22;

  // Connect to an SSH server and establish the SSH tunnel:
  try {
    tunnel.sshOpenTunnel(sshHostname, sshPort);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Authenticate with the SSH server via a login/password
  // or with a public key.
  // This example demonstrates SSH password authentication.
  try {
    tunnel.sshAuthenticatePw('mySshLogin', 'mySshPassword');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  //  OK, the SSH tunnel is setup.  Now open a channel within the tunnel.
  //  (Any number of channels may be created from the same SSH tunnel.
  //  Multiple channels may coexist at the same time.)

  // This example connects to a REST server through the SSH tunnel.
  // It will connect to the Amazon AWS service for this example.
  final rest = CkRest();

  final bTls = true;
  final port = 443;
  final maxWaitMs = 5000;

  // This returns a socket object that is a single channel within the SSH tunnel.
  final channel = CkSocket();
  try {
    tunnel.sshNewChannel('s3.amazonaws.com', port, bTls, maxWaitMs, channel);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Use the connection.  (This connection is a TLS running on an SSH channel through an SSH tunnel.
  // In other words, TLS is wrapped within the SSH tunnel.)
  try {
    rest.useConnection(channel, true);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Provide AWS credentials for the REST call.
  final authAws = CkAuthAws();
  authAws.accessKey = 'AWS_ACCESS_KEY';
  authAws.secretKey = 'AWS_SECRET_KEY';
  authAws.serviceName = 's3';
  rest.setAuthAws(authAws);

  // List all buckets for the account...
  final String responseXml;
  try {
    responseXml = rest.fullRequestNoBody('GET', '/');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final xml = CkXml();
  xml.loadXml(responseXml);

  // Show the full XML returned.
  print(xml.getXml());

  // Iterate over the buckets, showing each bucket name.
  xml.findChild2('Buckets');
  if (xml.firstChild2()) {
    print(xml.getChildContent('Name'));
    while (xml.nextSibling2()) {
      print(xml.getChildContent('Name'));
    }
  }

  // Move the internal pointer back to the root node.
  xml.getRoot2();
}