Search code examples
androidkotlindynamichttp-headersokhttp

Kotlin okhttp dynamic header


i am using okhttp (not retrofit) to make all my request to the api. It's working perfectly but i am having some trouble to make dynamique header. here is what i did :

private fun buildRequest(url: String, methode: Method = Method.GET, filters: Map<String, String> = mapOf(): Request? {

var builder = FormBody.Builder()
builder.add("body", "test")
val request = Request.Builder()
                .url(url)
                .addHeader("API-Key", apikey)
                .post(formBody)
                .build()
}

Problem is that i got a map filter that represent some header i need to add, but those are not hard coded but they are dynamique, it can be for exemple :

var filters = mapOf("limit" to "10", "sort" to "date")

But i can't do a static addHeader for the filters because i don't know if i am going to have some or not or which are they going to be.

My idea was to use newBuilder like this :

if (!filters.isNullOrEmpty()){
    filters.forEach{
       request.newBuilder()
       request.addHeader(it.key, it.value)
              .build()

}

Problem is that this doesn't add my new header to the call. I am I missing something on how to use newBuilder ? or is there a way to manage dynamique header with okhttp ?


Solution

  • You can use toHeaders() extension function of map to convert your map object to Headers.

    All key-value pairs of the map can be easily added to headers like this

    val request = Request.Builder()
                    .url(url)
                    .headers(filters.toHeaders())
                    
    

    Note - Using headers() would replace all previously added headers of the request builder.

    You can also add headers to request builder later, on using newBuilder()

    request.newBuilder()
         .headers(filters.toHeaders())