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

A1Blocker - Hide Apps

Hide Apps from Home Screen, App Library and Lock Apps to protect your privacy even further (requires iOS 16).

DNS Firewall for iOS

Encrypted your DNS to protect your privacy and firewall to block phishing, malicious domains, block ads in all browsers and apps

Ad