Retrofit2: Modifying request body in OkHttp Interceptor

前端 未结 4 1908
遥遥无期
遥遥无期 2020-12-01 15:37

I am using Retrofit 2 (2.0.0-beta3) with OkHttp client in Android application and so far everything going great. But currently I am facing issue with OkHttp Interceptor. The

4条回答
  •  醉梦人生
    2020-12-01 16:23

    I'll share my Kotlin implementation of @Fabian's answer using Dagger. I wanted origin=app added to the request url for GET requests, and added to the body for form-encoded POST requests

    @Provides
    @Singleton
    fun providesRequestInterceptor() =
            Interceptor {
                val request = it.request()
    
                it.proceed(when (request.method()) {
                    "GET" -> {
                        val url = request.url()
                        request.newBuilder()
                                .url(url.newBuilder()
                                        .addQueryParameter("origin", "app")
                                        .build())
                                .build()
                    }
                    "POST" -> {
                        val body = request.body()
                        request.newBuilder()
                                .post(RequestBody.create(body?.contentType(),
                                        body.bodyToString() + "&origin=app"))
                                .build()
                    }
                    else -> request
                })
            }
    
    fun RequestBody?.bodyToString(): String {
        if (this == null) return ""
        val buffer = okio.Buffer()
        writeTo(buffer)
        return buffer.readUtf8()
    }
    

提交回复
热议问题