I couldn't find a way to add an header only in case it doesn't exist.
What I actually need is to add the default header
"Content-Type": "application/json"
but only in case the header doesn't exist already.
One way to do it would be to have a different Http client or a different interceptor for when the default is necessary but I was expecting to be able to check whether the header is already there and add it only in case it is not.
This is definitely possible, but it also depends where you do it.
val i = Interceptor {
val request = if (it.request().header("A") != null) it.request() else it.request()
.newBuilder()
.header("A", "xxx")
.build()
val response = it.proceed(request)
if (response.header("A") != null) response else response
.newBuilder()
.header("A", "xxx")
.build()
}
But Content-Type is special because it is usually carried on the RequestBody, or ResponseBody. The BridgeInterceptor sits between the application interceptors and network interceptors.
val contentType = body.contentType()
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString())
}
and