Ktor sets default User-Agent even though custom one is defined in Default Headers
See original GitHub issueKtor Version and Engine Used (client or server and name) ktor-client-apache:1.3.1
Describe the bug
Default “Ktor client” User-Agent
is set even if User-Agent
header value was previously configured using .setDefaultHeaders()
for client.
To Reproduce Steps to reproduce the behavior:
- Create client instance and setDefaultHeader
User-Agent
:
val client = HttpClient(Apache) {
engine {
customizeClient {
setDefaultHeaders(mapOf(
"User-Agent" to "Test Agent"
).map { BasicHeader(it.key, it.value) })
}
}
}
- Perform any request:
client.request<String>("https://google.com/") {
method = HttpMethod.Get
}
Expected behavior
Request is done using User-Agent
that was configured for the client using default headers and not default User-Agent for Ktor
Result
Request is done using default Ktor UA header: Ktor client
and not Test Agent
that was sent when initializing client
Code issues
The problem is in ktor-client-core-jvm-1.3.1-sources.jar!/commonMain/io/ktor/client/engine/Utils.kt
class. It checks if there’s UA header in request itself or in content headers but never checks client default headers.
Here are the corresponding lines of code:
val missingAgent = requestHeaders[HttpHeaders.UserAgent] == null && content.headers[HttpHeaders.UserAgent] == null
if (missingAgent && needUserAgent()) {
block(HttpHeaders.UserAgent, KTOR_DEFAULT_USER_AGENT)
}
Workaround
Set User-Agent
header for every request instead of setting it 1 time for the client
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (3 by maintainers)
Top GitHub Comments
Hi @dtolstyi, thanks for reporting! I’m working on it, but meanwhile, as a workaround, you could use
UserAgent
feature to set the user agent:I see. Thank you for your answer @dmitrievanthony. Should we use
defaultRequest
block to specify default headers using ktor infrastructure?