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 :)
Edit
- jsonBody function add implicitly header "Content-Type" to "application/json"
- If apiKey can't be use in v3, which other way can I use ? I already have firebase Crashlytics, it means I already have a google service to potentially handle a communication to a google service but there's way too much documentation going all over the place, it's just terrible, it makes me sick. Which library can I use to handle credential in android application without breaking my app for "Meta-*** conflict", etc. I'm confused and lost in this ocean of information.
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