Android Question Google translate API REST authentic

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Hi all!
I'm trying to post, but I'm doing something wrong.

create a service account as indicated in the toturial and save the credential in GOOGLE_APLICATIONS_CREDENCIALS

Instructiones google API REST Translate:

HTTP method and URL:
POST https://translation.googleapis.com/language/translate/v2
JSON body of the request:
{
"q": ["Hello world"],
"target": "de"
}

Save the body of the request in a file called request.json and run the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \

My code:

B4X:
    Dim translate As Map
    translate.Initialize
    translate.Put("q","hello word")
    translate.Put("target","de")
   
    Dim job1 As HttpJob
    Dim jg As JSONGenerator
    jg.Initialize(translate)
    job1.Tag=jg
   
   
    job1.Initialize("@request.json",Me)
    job1.PostString("https://translation.googleapis.com/language/translate/v2",jg.ToString)
    job1.GetRequest.SetHeader("Authorization","Bearer $(gcloud auth application-default print-access-token)")  '<-- ITS BAD
    job1.GetRequest.SetContentType("application/json;charset=UTF-8")



I'm sure this line is wrong, because I should be able to point to job1.GetRequest.SetHeader("Authorization","Bearer $(gcloud auth application-default print-access-token)") '<-- ITS BAD

I'm not sure this is solving it right either -d @ request.json

I appreciate you can help me
 

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
HI, I was able to make it work another way, it uses an API key

B4X:
Dim translate As Map
    translate.Initialize
    translate.Put("target", dst) '-> lenguage
    translate.Put("q", texto) '- text translate
   
    Dim json As JSONGenerator
    json.Initialize(translate)
   
    Dim job As HttpJob:job.Initialize("@request.json", Me)
   
    Dim API_KEY As String="AIzxxxxxxxxxxxxxxxxxxxx" '<--APIKEY '

    Dim poststr As String = "https://translation.googleapis.com/language/translate/v2?key="&API_KEY
    job.PostString(poststr, json.ToString)
    job.GetRequest.SetContentType("application/json; charset=utf-8")

    Wait For (job) JobDone(job As HttpJob)
        If job.Success Then
            Try
                Dim jsonParser As JSONParser
                jsonParser.Initialize(job.GetString)
               
                Log(jsonParser.NextObject.Get("data"))
               
               
            Catch
                Log(LastException)
            End Try
        Else
            Log(job.ErrorMessage)
        End If

regards and sorry
 
Last edited:
Upvote 0
Top