React Native & okhttp on Android - Set User-Agent

前端 未结 4 1035
梦如初夏
梦如初夏 2020-12-10 15:42

I\'m trying to set the User-Agent with React Native on Android. Did some research and it looks like I should use an okhttp Interceptor

4条回答
  •  情书的邮戳
    2020-12-10 15:53

    Old issue, but we still ran into the same problem with React Native 0.59. This is what we did to fix (in Kotlin), as recent versions of okhttp prevent (and throw an exception) when trying to add an interceptor to an already initialized client:

    import android.os.Build
    import com.facebook.react.modules.network.OkHttpClientFactory
    import com.jaredrummler.android.device.DeviceName
    import okhttp3.Interceptor
    import okhttp3.OkHttpClient
    import okhttp3.Response
    
    class UserAgentInterceptor(val userAgent: String): Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val originalRequest = chain.request()
    
            val correctRequest = originalRequest.newBuilder()
                    .removeHeader("User-Agent")
                    .addHeader("User-Agent", userAgent)
                    .build()
            return chain.proceed(correctRequest)
        }
    }
    
    class UserAgentClientFactory(val appName: String, val appVersion: String, val buildNumber: String): OkHttpClientFactory {
        private fun userAgentValue(): String {
            val deviceName = DeviceName.getDeviceName()
            val osVersion = Build.VERSION.RELEASE
            return "$appName/$appVersion (build: $buildNumber; device: $deviceName; OS: Android $osVersion)"
        }
    
        override fun createNewNetworkModuleClient(): OkHttpClient {
            val builder = com.facebook.react.modules.network.OkHttpClientProvider.createClientBuilder()
            return builder.addInterceptor(UserAgentInterceptor(userAgent = userAgentValue())).build()
        }
    }
    

    This was done in a shared library between 2 apps, thus why we passed in the app name, version, and build number.

    Usage from the app itself looked like:

    private fun configureUserAgent() {
        val versionName = BuildConfig.VERSION_NAME
        val versionCode = BuildConfig.VERSION_CODE
        OkHttpClientProvider.setOkHttpClientFactory(UserAgentClientFactory(appName = "My App", appVersion = versionName, buildNumber = "$versionCode"))
    }
    

    This was called from the onCreate method in the main activity of the app.

    Hope this helps!

提交回复
热议问题