I’m having trouble converting my working OkHttp code to use Retrofit instead. I have a working OkHttp implementation that calls a translation service, but when I try to recreate the same request using Retrofit, it doesn’t work properly.
Here’s my current OkHttp code that works fine:
val httpClient = OkHttpClient()
val contentType = MediaType.parse("application/x-www-form-urlencoded")
val requestBody = RequestBody.create(contentType, "text=Good%20morning&lang=fr")
val httpRequest = Request.Builder()
.url("https://translate-service.p.rapidapi.com/v2/translate")
.post(requestBody)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("Accept-Encoding", "application/gzip")
.addHeader("X-RapidAPI-Host", "translate-service.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", MY_API_KEY)
.build()
val result = httpClient.newCall(httpRequest).execute()
I’m trying to convert this to Retrofit but not sure about the correct approach. Here’s what I have so far:
interface TranslationService {
@Headers(
"content-type: application/x-www-form-urlencoded",
"Accept-Encoding: application/gzip",
"X-RapidAPI-Host: translate-service.p.rapidapi.com",
"X-RapidAPI-Key: MY_API_KEY"
)
@POST("v2/translate")
suspend fun performTranslation(
@Body text: String,
@Query("lang") language: String,
@Query("source") sourceLanguage: String
): Response<TranslationResponse>
}
What am I doing wrong with the Retrofit setup?