Перехватчик с модификацией заголовка и тела:
class OkHttpInterceptor() : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val requestWithAndroidHeaders = addHeaderFields(request)
val response = chain.proceed(requestWithAndroidHeaders)
return modifyResponseBody(response)
}
private fun addHeaderFields(request: Request): Request = request.newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("User-Agent", "Android")
.addHeader("TraceId", "abc 123")
.build()
private fun modifyResponseBody(response: Response): Response {
val responseString = response.body()?.charStream()?.readText()
val responseJson = responseString?.let { stringToJson(it) }
return if (responseJson != null) {
val contentType: MediaType? = response.body()?.contentType()
val responseBody = ResponseBody.create(contentType, responseJson.toString())
response.newBuilder().body(responseBody).build()
} else {
response
}
}
private fun stringToJson(responseString: String): JSONObject? = try {
JSONObject(responseString).put("traceId", "abc 123")
} catch (e: JSONException) {
println(e.message)
null
}
}
OkHttpClient:
val okHttpInterceptor = OkHttpInterceptor()
val client = OkHttpClient.Builder()
client.interceptors().add(okHttpInterceptor)
client.build()
Возможно, вы также хотите добавить Логирование:
val logging = HttpLoggingInterceptor()
if(BuildConfig.DEBUG) {
logging.level = HttpLoggingInterceptor.Level.BODY
} else {
logging.level = HttpLoggingInterceptor.Level.NONE
}
val okHttpInterceptor = OkHttpInterceptor()
val client = OkHttpClient.Builder()
client.interceptors().add(okHttpInterceptor)
client.interceptors().add(logging)
client.build()