HTTP headers
suggest changeHTTP headers allow clients and servers to pass metadata alongside HTTP requests and responses. They govern content negotiation, authentication, caching policies, cookies, and CORS restrictions.
In Kotlin, HTTP headers are handled primarily using modern libraries such as Ktor Client & Server, OkHttp, and the standard Java java.net.http.HttpClient.
Key Concepts
- Case Insensitivity: Header names are ASCII case-insensitive according to RFC 7230 (
Content-Typeis equivalent tocontent-type). - Multi-Valued Headers: Headers like
Accept,Set-Cookie, or custom headers can contain multiple comma-delimited values or multiple header lines. - Common Categories:
- Representation:
Content-Type,Content-Length,Content-Encoding - Authentication:
Authorization,WWW-Authenticate,Proxy-Authorization - Client Preferences:
Accept,Accept-Language,User-Agent - Caching:
Cache-Control,ETag,If-None-Match,Expires
- Representation:
Reading and Setting Headers with Ktor Client
Ktor is JetBrains' multiplatform asynchronous HTTP client and server framework. Ktor provides type-safe constants in io.ktor.http.HttpHeaders.
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
suspend fun ktorHeadersExample() {
val client = HttpClient(CIO)
// Sending headers in a request
val response: HttpResponse = client.get("https://api.example.com/data") {
// Using standard header extension methods
header(HttpHeaders.Accept, "application/json")
header(HttpHeaders.UserAgent, "MyApp/1.0 (Kotlin)")
// Setting bearer token authorization
bearerAuth("my-secret-jwt-token")
// Custom headers
header("X-Request-ID", "req-98765-xyz")
}
println("Status: ${response.status}")
// Inspecting response headers
val contentType: String? = response.headers[HttpHeaders.ContentType]
val contentLength: Long? = response.headers[HttpHeaders.ContentLength]?.toLongOrNull()
val requestId: String? = response.headers["X-Request-ID"]
println("Content-Type: $contentType")
println("Content-Length: $contentLength")
println("Request ID: $requestId")
// Iterating all received headers
for ((name, values) in response.headers.entries()) {
println("$name: ${values.joinToString(", ")}")
}
client.close()
}
Installing Default Headers across Requests
In Ktor, you can install plugins to automatically inject headers (such as User-Agent or authentication) on every outgoing request:
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.request.*
import io.ktor.http.*
val client = HttpClient(CIO) {
defaultRequest {
header(HttpHeaders.Accept, "application/json")
header("X-App-Version", "2.4.0")
}
install(UserAgent) {
agent = "KotlinApp/1.0.0"
}
}
Handling Headers in Ktor Server
When building microservices or APIs with Ktor Server, headers are accessed via call.request.headers and set via call.response.header():
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureRouting() {
routing {
get("/api/profile") {
// Reading request headers
val authHeader: String? = call.request.headers[HttpHeaders.Authorization]
val clientIp: String? = call.request.headers["X-Forwarded-For"]
?: call.request.local.remoteAddress
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
call.response.header(HttpHeaders.WWWAuthenticate, "Bearer realm=\"Access to profile\"")
call.respond(HttpStatusCode.Unauthorized, "Missing or invalid authorization header")
return@get
}
// Setting custom and standard response headers
call.response.header(HttpHeaders.CacheControl, "no-store, max-age=0")
call.response.header("X-Handled-By", "node-eu-west-1")
call.respondText(
text = """{"id": 42, "status": "active"}""",
contentType = ContentType.Application.Json
)
}
}
}
Using OkHttp
OkHttp is widely used across Kotlin backend and Android applications. Its Headers class provides immutable, case-insensitive mapping with builder support.
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
fun okHttpExample() {
val client = OkHttpClient()
// Building headers
val requestHeaders = Headers.Builder()
.add("Accept", "application/json")
.add("Authorization", "Bearer eyJhbGciOi...")
.add("X-Correlation-ID", "corr-123456")
.build()
val request = Request.Builder()
.url("https://httpbin.org/headers")
.headers(requestHeaders)
.build()
client.newCall(request).execute().use { response ->
println("Response Code: ${response.code}")
// Reading single value
val server = response.header("Server", "Unknown")
println("Server: $server")
// Reading multiple values for same header name
val cookies: List<String> = response.headers("Set-Cookie")
cookies.forEach { cookie ->
println("Cookie: $cookie")
}
// Iterating all response headers
response.headers.forEach { (name, value) ->
println("$name: $value")
}
}
}
Interceptor for Global Headers in OkHttp
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class AuthHeaderInterceptor(private val apiKey: String) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val authenticatedRequest = originalRequest.newBuilder()
.header("X-API-Key", apiKey)
.header("User-Agent", "KotlinService/1.0")
.build()
return chain.proceed(authenticatedRequest)
}
}
val clientWithInterceptor = OkHttpClient.Builder()
.addInterceptor(AuthHeaderInterceptor("secret-token-xyz"))
.build()
Standard Java 11+ java.net.http.HttpClient
Without external dependencies, Kotlin projects running on JVM 11+ can use java.net.http:
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
fun standardJavaHttpClient() {
val client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build()
val request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/get"))
.timeout(Duration.ofSeconds(5))
.header("Accept", "application/json")
.header("X-Client-Trace", "trace-789")
// Set replaces previous values; header appends
.setHeader("User-Agent", "Java11-KotlinClient/1.0")
.GET()
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
// Accessing java.net.http.HttpHeaders
val headers = response.headers()
// First value lookup
val contentType = headers.firstValue("content-type").orElse("none")
println("Content-Type: $contentType")
// Map of all header lists
headers.map().forEach { (name, values) ->
println("$name = $values")
}
}
Best Practices
- Use Constants for Standard Headers: Avoid string typos by using
HttpHeaders.ContentType(in Ktor) or standard string constants instead of raw strings like"content-type". - Never Log Sensitive Headers: Scrub headers such as
Authorization,Proxy-Authorization,Cookie, andSet-Cookiein application logs. - Handle Multi-value Headers Appropriately: Headers such as
Set-Cookiecannot be combined with commas because expires attributes use commas in dates. Always useheaders.getAll()or equivalent multi-line readers. - Prefer
.header()vs.setHeader(): In JavaHttpRequest.Builder,.header(k, v)appends to existing values while.setHeader(k, v)overwrites. Be explicit about whether replacement or addition is intended.