Sample code for 30+ languages & platforms
B4X

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 B4X Downloads

B4X
Dim success As Boolean = False

'  This example requires the Chilkat API to have been previously unlocked.
'  See Global Unlock Sample for sample code.

Dim rest As ChilkatRest
rest.Initialize("rest")

Dim authAws As ChilkatAuthAws
authAws.Initialize
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/
Dim bTls As Boolean = True
Dim port As Int = 443
Dim bAutoReconnect As Boolean = True
success = rest.Connect("translate.us-west-2.amazonaws.com", port, bTls, bAutoReconnect)
If success <> True Then
    Log("ConnectFailReason: " & rest.ConnectFailReason)
    Log(rest.LastErrorText)
    Return
End If


'  Translate text from English to German
Dim json As ChilkatJsonObject
json.Initialize
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")

Dim sbRequestBody As ChilkatStringBuilder
sbRequestBody.Initialize
json.EmitSb(sbRequestBody)
Dim sbResponseBody As ChilkatStringBuilder
sbResponseBody.Initialize
success = rest.FullRequestSb("POST", "/", sbRequestBody, sbResponseBody)
If success <> True Then
    Log(rest.LastErrorText)
    Return
End If

Dim respStatusCode As Int = rest.ResponseStatusCode
If respStatusCode >= 400 Then
    Log("Response Status Code = " & respStatusCode)
    Log("Response Header:")
    Log(rest.ResponseHeader)
    Log("Response Body:")
    Log(sbResponseBody.GetAsString)
    Return
End If


Dim jsonResponse As ChilkatJsonObject
jsonResponse.Initialize
jsonResponse.LoadSb(sbResponseBody)
jsonResponse.EmitCompact = False

Log(jsonResponse.Emit)

'  {
'    "SourceLanguageCode": "en",
'    "TargetLanguageCode": "de",
'    "TranslatedText": "Dies ist der zu �bersetzende Text"
'  }

Log(jsonResponse.StringOf("TranslatedText"))