I am a beginner with Retrofit and I need help using the Google Translate API via RapidApi. My challenge is translating an OkHttp code example into Retrofit format. Below is the OkHttp implementation for a POST request:
val httpClient = OkHttpClient()
val requestMediaType = MediaType.parse("application/x-www-form-urlencoded")
val requestBody = RequestBody.create(requestMediaType, "q=Hello%2C%20world!&target=es")
val httpRequest = Request.Builder()
.url("https://google-translate1.p.rapidapi.com/language/translate/v2")
.post(requestBody)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("Accept-Encoding", "application/gzip")
.addHeader("X-RapidAPI-Host", "google-translate1.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", API_KEY)
.build()
val httpResponse = httpClient.newCall(httpRequest).execute()
Now, I’d like to replicate this request using Retrofit in my Android app. Here is the API interface I’ve created:
interface TranslationService {
@Headers(
"content-type: application/x-www-form-urlencoded",
"Accept-Encoding: application/gzip",
"X-RapidAPI-Host: google-translate1.p.rapidapi.com",
"X-RapidAPI-Key: API_KEY"
)
@POST("translate/v2")
suspend fun performTranslation(
@Body query: String,
@Query("target") targetLang: String,
@Query("source") sourceLang: String
): Response<TranslationResult>
}