'OKHttp Add header only if it doesn't already exist
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yuri Schimke |
