UrlFormEncoded post 请求中的字段被编码两次

Fields in UrlFormEncoded post requests are encoded twice

我正在尝试通过改造发送身份验证(登录)POST 请求,这是改造服务接口:


interface AuthApiService {

    @POST("customer/login/")
    @FormUrlEncoded
    suspend fun login(
        @FieldMap(encoded = true) parameters: Map<String, String>,
    ): Customer
}

问题是 parameters 地图的字段参数被 URL 编码 两次 ,例如电子邮件 email@gmail.com 是作为 email%2540gmail.com 而不是 email%40gmail.com.

发送

我试过设置@FieldMap(encoded = false),还是一样

我什至试过这个:

@POST("customer/login/")
    @FormUrlEncoded
    suspend fun login(
        @Field("email",encoded = true) email:String,
        @Field("password",encoded = true) password:String
    ): Customer

还有这个:

@POST("customer/login/")
    @FormUrlEncoded
    suspend fun login(
        @Field("email",encoded = false) email:String,
        @Field("password",encoded = false) password:String
    ): Customer

但运气不好。

原来我的问题出在我的请求拦截器 class:

class BaseRequestInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
        val body = request.body as FormBody

        val map = mutableMapOf<String, String>()

        with(body) {
            for (x in 0 until size) {
                // ######## here was the problem ########
                map[encodedName(x)] = encodedValue(x)
            }
        }

        // adding universal fields for every request
        map["field_key1"] = "field_value1"
        map["field_key2"] = "field_value2"

        val newFormBody = FormBody.Builder().apply {
            map.forEach {
                add(it.key, it.value)
            }
        }.build()

        request = request.newBuilder().apply {
            post(newFormBody)
        }.build()

        return chain.proceed(request)
    }

}

我通过替换行解决了问题:

map[encodedName(x)] = encodedValue(x)

与:

map[name(x)] = value(x)