React Native
React Native
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 React Native Downloads
import { AuthAws, JsonObject, Rest, StringBuilder } from '@chilkat/react-native'
async function chilkatExample() {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const rest = new Rest();
const authAws = new AuthAws();
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/
const bTls = true;
const port = 443;
const bAutoReconnect = true;
try {
await rest.connectAsync('translate.us-west-2.amazonaws.com', port, bTls, bAutoReconnect);
} catch {
console.log(`ConnectFailReason: ${rest.connectFailReason}`);
console.log(rest.lastErrorText);
return;
}
// Translate text from English to German
const json = new JsonObject();
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');
const sbRequestBody = new StringBuilder();
json.emitSb(sbRequestBody);
const sbResponseBody = new StringBuilder();
try {
await rest.fullRequestSbAsync('POST', '/', sbRequestBody, sbResponseBody);
} catch {
console.log(rest.lastErrorText);
return;
}
const respStatusCode = rest.responseStatusCode;
if (respStatusCode >= 400) {
console.log(`Response Status Code = ${respStatusCode}`);
console.log('Response Header:');
console.log(rest.responseHeader);
console.log('Response Body:');
console.log(sbResponseBody.getAsString());
return;
}
const jsonResponse = new JsonObject();
jsonResponse.loadSb(sbResponseBody);
jsonResponse.emitCompact = false;
console.log(jsonResponse.emit());
// {
// "SourceLanguageCode": "en",
// "TargetLanguageCode": "de",
// "TranslatedText": "Dies ist der zu �bersetzende Text"
// }
console.log(jsonResponse.stringOf('TranslatedText'));
}