Search code examples
androidokhttpinterceptor

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

  • 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.

    See https://github.com/square/okhttp/blob/5c62ed796d05682c969b2636d3419b5bc214eb11/okhttp/src/jvmMain/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L43-L46

          val contentType = body.contentType()
          if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString())
          }
    

    and

    https://github.com/square/okhttp/blob/5c62ed796d05682c969b2636d3419b5bc214eb11/okhttp/src/jvmMain/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L102-L103