Monday, 16 November 2020

How to convert googleapis/java-translate library to custom api rest request using google translation api v3 in an Android project

Before seeing conflicts when building a release for my app because of googleapis/java-translate library, I used these lines and it worked perfectly :

val translate: Translate = TranslateOptions.newBuilder().setApiKey(API_KEY).build().service
val translations = translate.translate(
     textsToTranslate,
     Translate.TranslateOption.sourceLanguage(sourceLanguage),
     Translate.TranslateOption.targetLanguage(targetLanguage)
)

Then, when building release, I had to add some extra code in app/build.gradle to make it works. But, I saw that my app grows from 10Mo to 15Mo. Expensive just for translating some texts..

So I decide to perform these translations by myself using the latest Google Translate Api v3 link

Perform a simple api rest request like this :

val jsonObjectResponse = JSONObject(translate(sourceLanguageCode = sourceLanguage, targetLanguageCode = targetLanguage, textsToTranslate).awaitString())
val translations = jsonObjectResponse.getJSONArray("translations").toArray { getJSONObject(it) }.map { it.getString("translatedText") }

where "translate" function is :

private fun translate(sourceLanguageCode: String, targetLanguageCode: String, textsToTranslate: List<String>): Request =
    Fuel.post(path = "https://translation.googleapis.com/v3/projects/$PROJECT_ID:translateText?key=$API_KEY")
        .header(Headers.ACCEPT to "application/json")
        .jsonBody(
            JSONObject().apply {
                put("contents", JSONArray().apply {
                    textsToTranslate.forEach { text -> put(text) }
                })
                put("sourceLanguageCode", sourceLanguageCode)
                put("targetLanguageCode", targetLanguageCode)
            }.toString()
        )

but it returns : "HTTP Exception 401 Unautorhorized". The link doesn't mention usage of API_KEY so I suppose it's related to..

Note : Fuel is just a HTTP networking library for Kotlin/Android to avoid boiler plate code.

To resume: the first one using googleapis/java-translate was working but the second (custom) doesn't work and returns : "HTTP Exception 401 Unautorhorized".

Where am I wrong ?

Extra note: I know I'm not restricting right now to the package name of the android app but here, I just want to make it works :)



from How to convert googleapis/java-translate library to custom api rest request using google translation api v3 in an Android project

No comments:

Post a Comment