I refer to the example codes for google translate:
https://www.b4x.com/android/forum/threads/google-translate-api.75924/#content
The example code is not working anymore because (I guess) the free API is blocked. Where in the code can I insert an API key?
In the different google rest services the api key is usually given as a get value and the accesstoken is used in a Authorisation header.... (Bearer Token)
Error: java.net.UnknownHostException: Unable to resolve host "translate.googleapis.com": No address associated with hostname
Google is working as the forum search here.
You just need to use it
https://cloud.google.com/translate/docs/reference/rest/
Based on the docs this domain still exists?
Pinging it at commandprompt does work
Sub Translate (jobnamekey As String,sourcelang As String,destlang As String)
Dim job As HttpJob
job.Initialize(jobnamekey,Me)
job.Tag = counttrans
'Use Google Free google API translate
job.PostString($"https://Translate.googleapis.com/translate_a/single?client=gtx&sl=${sourcelangname}&tl=${destlangname}&dt=t&q=${jobnamekey}"$,"")
job.GetRequest.SetHeader("Content-Type", "application/json")
job.GetRequest.SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0")
job.GetRequest.SetContentType("application/json")
job.GetRequest.SetContentEncoding("text/plain")
End Sub
Based on https://cloud.google.com/translate/docs/quickstart you need to use a AccessToken (which you get using OAuth2) in a Authorisationheader.
No key is used it seems.
Edit to add: Rest reference.
https://cloud.google.com/translate/docs/translating-text#translate_translate_text-cli-curl
curl is a good one to see how it works. It can be easily translated into okhttputils calls.
As written above you need to get an Accesstoken using OAuth2 Class to get an AccessToken. You need to create a OAuthclient in your Google Cloud Console and add the correct Api to use to this Client.
Again and a last try to help:may I ask where the client ID can be found?
Sub Trans(srclang As String, dstlang As String, transtr As String)
'https://cloud.google.com/translate/docs/reference/rest/v3beta1/projects/translateText
Dim mapReq As Map:mapReq.Initialize
mapReq.Put("sourceLanguageCode",srclang)
mapReq.Put("targetLanguageCode", dstlang)
Dim lstContent As List:lstContent.Initialize:lstContent.Add("transtr")
mapReq.Put("contents", transtr)
Dim json As JSONGenerator:json.Initialize(mapReq)
Dim job As HttpJob:job.Initialize("xlate", Me)
Dim Parent As String="{parent=projects/*}"
' Parent: Required. Project Or location To make a call. Must refer To a caller's project.
' Format: projects/{project-id} Or projects/{project-id}/locations/{location-id}.
' For global calls, use projects/{project-id}/locations/global Or projects/{project-id}.
' Non-global location Is required For requests using AutoML models Or custom glossaries.
' Models And glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error Is returned.
Dim API_KEY As String="YOUR API KEY HERE"
Dim poststr As String = "https://translation.googleapis.com/v3beta1/"&Parent&":translateText?key="&API_KEY
job.PostString(poststr, json.ToString)
job.GetRequest.SetContentType("application/json; charset=utf-8")
Wait For (job) JobDone(job As HttpJob)
Try
If job.Success Then
Try
Dim jsonParser As JSONParser
jsonParser.Initialize(job.GetString)
Dim lstTranslations As List=jsonParser.NextObject.Get("translations")
Dim mapTranslatedText As Map=lstTranslations.Get(0)
Dim strTranslatedText As String=mapTranslatedText.Get("translatedText")
Log("Tranlated Text: "&strTranslatedText)
Catch
Log(LastException)
End Try
Else
Log(job.ErrorMessage)
End If
Catch
ToastMessageShow(LastException.Message,False)
End Try
End Sub
This API no longer works correctly. You can use Google's Cloud Translation Beta3. You can also use the API Explorer: https://cloud.google.com/translate/docs/reference/rest/v3beta1/projects/translateText
Generate an API key ad described here: https://translatepress.com/docs/settings/generate-google-api-key
This is a sample code for B4x (not tested):
B4X:Sub Trans(srclang As String, dstlang As String, transtr As String) 'https://cloud.google.com/translate/docs/reference/rest/v3beta1/projects/translateText Dim mapReq As Map:mapReq.Initialize mapReq.Put("sourceLanguageCode",srclang) mapReq.Put("targetLanguageCode", dstlang) Dim lstContent As List:lstContent.Initialize:lstContent.Add("transtr") mapReq.Put("contents", transtr) Dim json As JSONGenerator:json.Initialize(mapReq) Dim job As HttpJob:job.Initialize("xlate", Me) Dim Parent As String="{parent=projects/*}" ' Parent: Required. Project Or location To make a call. Must refer To a caller's project. ' Format: projects/{project-id} Or projects/{project-id}/locations/{location-id}. ' For global calls, use projects/{project-id}/locations/global Or projects/{project-id}. ' Non-global location Is required For requests using AutoML models Or custom glossaries. ' Models And glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error Is returned. Dim API_KEY As String="YOUR API KEY HERE" Dim poststr As String = "https://translation.googleapis.com/v3beta1/"&Parent&":translateText?key="&API_KEY job.PostString(poststr, json.ToString) job.GetRequest.SetContentType("application/json; charset=utf-8") Wait For (job) JobDone(job As HttpJob) Try If job.Success Then Try Dim jsonParser As JSONParser jsonParser.Initialize(job.GetString) Dim lstTranslations As List=jsonParser.NextObject.Get("translations") Dim mapTranslatedText As Map=lstTranslations.Get(0) Dim strTranslatedText As String=mapTranslatedText.Get("translatedText") Log("Tranlated Text: "&strTranslatedText) Catch Log(LastException) End Try Else Log(job.ErrorMessage) End If Catch ToastMessageShow(LastException.Message,False) End Try End Sub
I will test the code in a few days and make sure it works
I scraped this.Not quite understand about the project-id part, I.e. the parent string. May I have more hints about that?
Sub bnTrans_Click
Dim job As HttpJob
Dim transtr As String = edIn.Text
Dim jobname As String = "xlate"
Dim jobtag As String = "french"
job.Initialize(jobname, Me)
job.Tag = jobtag
' Use Google Free google API translate
Dim srclang As String = "en"
Dim dstlang As String = "hi"
Dim poststr As String = "https://Translate.googleapis.com/translate_a/single?client=gtx&sl=" & _
srclang & "&tl=" & dstlang & "&dt=t&q=" & transtr
job.Download(poststr)
lbOut.Text = ""
End Sub
Sub JobDone (Job As HttpJob)
Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
If (Job.Success = True) Then
Dim trans As String = Job.GetString
Log(trans)
'========Modified code to take only the first "Double quote Value"
Dim count=0, i=0 As Int
Do While i<2
If trans.SubString2(count, count+1)=$"""$ Then i=i+1
count=count+1
Loop
trans=trans.SubString2(0, count)
'========Modified code Over to take only the first "Double quote Value"
Log(trans)
Dim rlst As List = MyParser(trans)
Log(rlst.Size)
For Each sa() As String In rlst
If (sa.Length > 0) Then
If (lbOut.Text <> "") Then lbOut.Text = lbOut.Text & CRLF
lbOut.Text = lbOut.Text & sa(0)
End If
Next
Else
Log("Error: " & Job.ErrorMessage)
ToastMessageShow("Error: " & Job.ErrorMessage, True)
End If
Job.Release
End Sub
Sub MyParser(js As String) As List ' returns list of string arrays
Dim rlst As List
Dim sa1(), str As String
Dim p As Int
rlst.Initialize
sa1 = Regex.Split("]", js)
For Each s1 As String In sa1
p = s1.LastIndexOf("[")
If (p < 0) Then Continue
str = s1.SubString2(p + 1, s1.Length)
str = str.Replace(QUOTE, "")
Dim sa2() As String = Regex.Split(",", str)
rlst.Add(sa2)
Next
Return(rlst)
End Sub
You need to have a billing account configured.To get Google API KEY, it is necessary to pay the service?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?