Ktorfit icon indicating copy to clipboard operation
Ktorfit copied to clipboard

FormUrlEncoded endpoints are not getting modified

Open theapache64 opened this issue 9 months ago • 2 comments

Ktorfit version

2.4.1

What happened and how can we reproduce this issue?

Issue

I've a @FormUrlEncoded endpoint. I am trying to modify the request using ClientPlugin. But both the existing param and the new params are not getting updated or added.

More details:

My interface

interface MyExampleApi {
    @FormUrlEncoded
    @POST("people/1/")
    suspend fun getPerson(
        @Field("key1") theKey: String,
        @Field("value1") theValue: String
    ): String
}

My client plugin

fun createRequestInterceptorPlugin(): ClientPlugin<Unit> {
    return createClientPlugin("RetrosheetRequestInterceptor") {
        onRequest { request, content ->
            (request.body as? FormDataContent)?.formData?.apply {
                plus(
                    Parameters.build {
                        // new
                        append("newKey", "i am new key")
                        append("newValue", "i am new value")

                        // existing
                        append("key1", "age")
                        append("value1", "1")
                    }
                )
                println("QuickTag: :createRequestInterceptorPlugin: intercepted")
            }
        }
    }
}

and my app code

suspend fun main() {
    val ktorClient = HttpClient {
        install(createRequestInterceptorPlugin()) {}
    }

    val api = Ktorfit.Builder()
        .baseUrl("https://reqres.in/api/")
        .httpClient(ktorClient)
        .build()
        .createMyExampleApi()

    api.getPerson("name", "foso").also {
        println(it)
    }
}

Actual It returns the original request

{
  "key1": "name",
  "value1": "foso"
}

Full Repro Code: https://github.com/theapache64/ktorfit-request-intercept-sample/tree/master

What did you expect to happen?

The API should echo back this response

{
  "key1": "age",
  "value1": "1",
  "newKey": "i am new key",
  "newValue": "i am new value"
}

Is there anything else we need to know about?

Environment: JVM

theapache64 avatar Mar 19 '25 01:03 theapache64

Few days after reporting this issue, I figured another function in the plugin called transformRequestBody that works well for my usecase. Keeping this issue open to confirm from someone if that's the right approach on modifying request body

theapache64 avatar Mar 26 '25 01:03 theapache64

hi @theapache64 thank you for reporting the issue!

Foso avatar Mar 30 '25 19:03 Foso