RSS

Android OkHttp change User-Agent header

Android OkHttp addHeader(“User-Agent”) does not work troubleshooting.

Symptom

Use OkHttpClient.Builder() to add User-Agent header.

val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor { chain ->
        val requestBuilder = chain.request().newBuilder()
            .addHeader("User-Agent", userAgent)

With this code, server does not get new User-Agent, it still use OkHttp default user agent, for example:

"User-Agent": "okhttp/3.14.9"

Troubleshooting

The OkHttp already have a default User-Agent, addHeader() does not override the default value.

Solution

Remove User-Agent header before call addHeader("User-Agent", ...):

val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor { chain ->
        val requestBuilder = chain.request().newBuilder()
            .removeHeader("User-Agent")  // otherwise addHeader not work.
            .addHeader("User-Agent", userAgent)

Reference