@@ -32,18 +32,22 @@ import java.net.http.HttpResponse
32
32
import java.util.Locale
33
33
import java.util.concurrent.CompletableFuture
34
34
import java.util.concurrent.Executor
35
+ import kotlinx.serialization.ExperimentalSerializationApi
35
36
import kotlinx.serialization.json.Json
36
- import kotlinx.serialization.json.JsonArray
37
- import kotlinx.serialization.json.JsonPrimitive
37
+ import kotlinx.serialization.json.addAll
38
+ import kotlinx.serialization.json.buildJsonObject
38
39
import kotlinx.serialization.json.jsonArray
39
40
import kotlinx.serialization.json.jsonObject
40
41
import kotlinx.serialization.json.jsonPrimitive
42
+ import kotlinx.serialization.json.put
43
+ import kotlinx.serialization.json.putJsonArray
41
44
42
45
// TODO Add backoff and retries (in case of 429)
43
46
internal class GoogleBasicTranslator (private val apiKey : String , executor : Executor ) : BaseTranslator() {
44
47
private val http = HttpClient .newBuilder().executor(executor).build()
45
48
internal val supported: Set <Locale > = fetchSupportedLanguages()
46
49
50
+ @OptIn(ExperimentalSerializationApi ::class )
47
51
override fun translateDetecting (
48
52
texts : List <String >,
49
53
source : Locale ,
@@ -72,21 +76,21 @@ internal class GoogleBasicTranslator(private val apiKey: String, executor: Execu
72
76
return CompletableFuture .completedFuture(List (texts.size) { i -> TranslatedText (texts[i], fixedSource) })
73
77
}
74
78
75
- val parameters =
76
- mutableMapOf (
77
- " key" to apiKey,
78
- " q" to JsonArray (texts.map(::JsonPrimitive )).toString(),
79
- " target" to fixedTarget.toLanguageTag(),
80
- " format" to " text" ,
81
- )
82
-
83
- if (fixedSource != Translator .AUTO_DETECT ) {
84
- parameters[" source" ] = fixedSource.toLanguageTag()
79
+ val json = buildJsonObject {
80
+ put(" key" , apiKey)
81
+ putJsonArray(" q" ) { addAll(texts) }
82
+ put(" target" , fixedTarget.toLanguageTag())
83
+ put(" format" , " text" )
84
+ if (fixedSource != Translator .AUTO_DETECT ) {
85
+ put(" source" , fixedSource.toLanguageTag())
86
+ }
85
87
}
86
88
87
89
return http
88
90
.sendAsync(
89
- HttpRequest .newBuilder(createApiUri(TRANSLATION_V2_ENDPOINT , parameters)).GET ().build(),
91
+ HttpRequest .newBuilder(createApiUri(TRANSLATION_V2_ENDPOINT ))
92
+ .POST (HttpRequest .BodyPublishers .ofString(json.toString()))
93
+ .build(),
90
94
HttpResponse .BodyHandlers .ofString(),
91
95
)
92
96
.thenCompose { response ->
0 commit comments