androidkotlinokhttp

OkHttp3 Request.Builder's post function won't accept FormBody as argument


Using OkHttp3 4.12.0 in Android Studio (2023.2.1 Patch 1) with Kotlin, I'm attempting to post a FormBody but the post function from Request.Builder() won't accept FormBody as an argument since it requires a RequestBody, even though the former extends the latter.

Even trying to use the example straight out of their documentation provides the same issue:

val formBody = FormBody.Builder()
    .add("search", "Jurassic Park")
    .build()

val request = Request.Builder()
     .url("https://en.wikipedia.org/w/index.php")
     .post(formBody)
     .build()
Type mismatch.
Required:
    RequestBody!
Found:
    FormBody

I can add as RequestBody to the end of the formBody definition which removes the warning from post but creates another that warns that this cast can never succeed

What am I missing, and what's the proper way to post a form body here?


Solution

  • The code looks fine, you probably have just the wrong Request class imported. It should be this:

    import okhttp3.Request