Dart
Dart
Amazon Translate Text
See more AWS Translate Examples
Demonstrates how to use the AWS Translate service to translate text from one language to another.Chilkat Dart Downloads
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 rest = CkRest();
final authAws = CkAuthAws();
authAws.accessKey = 'AWS_ACCESS_KEY';
authAws.secretKey = 'AWS_SECRET_KEY';
authAws.region = 'us-west-2';
authAws.serviceName = 'translate';
rest.setAuthAws(authAws);
// URL: https://translate.us-west-2.amazonaws.com/
final bTls = true;
final port = 443;
final bAutoReconnect = true;
try {
rest.connect('translate.us-west-2.amazonaws.com', port, bTls, bAutoReconnect);
} on ChilkatException catch (e) {
print('ConnectFailReason: ${rest.connectFailReason}');
print(e.lastErrorText);
return;
}
// Translate text from English to German
final json = CkJsonObject();
json.updateString('SourceLanguageCode', 'en');
json.updateString('TargetLanguageCode', 'de');
json.updateString('Text', 'This is the text to be translated');
rest.addHeader('Content-Type', 'application/x-amz-json-1.1');
rest.addHeader('X-Amz-Target', 'AWSShineFrontendService_20170701.TranslateText');
final sbRequestBody = CkStringBuilder();
json.emitSb(sbRequestBody);
final sbResponseBody = CkStringBuilder();
try {
rest.fullRequestSb('POST', '/', sbRequestBody, sbResponseBody);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final respStatusCode = rest.responseStatusCode;
if (respStatusCode >= 400) {
print('Response Status Code = $respStatusCode');
print('Response Header:');
print(rest.responseHeader);
print('Response Body:');
print(sbResponseBody.getAsString());
return;
}
final jsonResponse = CkJsonObject();
jsonResponse.loadSb(sbResponseBody);
jsonResponse.emitCompact = false;
print(jsonResponse.emit());
// {
// "SourceLanguageCode": "en",
// "TargetLanguageCode": "de",
// "TranslatedText": "Dies ist der zu �bersetzende Text"
// }
print(jsonResponse.stringOf('TranslatedText'));
}