Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,35 @@ import org.gradle.api.GradleException
import org.gradle.api.artifacts.component.ModuleComponentIdentifier

// Keep the normal build on the version in the catalog. This init script is only
// used by the compatibility job, so its compile and test classpaths use OkHttp 3.
// This catches new OkHttp 4-only calls before they need reverting (e.g. #60318).
// used by the compatibility jobs, so its compile and test classpaths use the
// OkHttp version passed with -PokhttpCompatVersion. OkHttp 3 catches new OkHttp
// 4-only calls before they need reverting (e.g. #60318). OkHttp 5 catches API and
// behavior changes that apps depending on it would hit. Those apps run the AAR
// built against the catalog version, so this does not check binary compatibility.
// OkHttp 5 also brings Okio 3, so the verification logs the Okio version too.
gradle.beforeProject { project ->
if (project.path != ':packages:react-native:ReactAndroid') {
return
}

def okhttpVersion = '3.14.9'
def okhttpVersion = project.findProperty('okhttpCompatVersion')
if (!okhttpVersion) {
throw new GradleException('Pass the OkHttp version to check, e.g. -PokhttpCompatVersion=3.14.9')
}

project.configurations.configureEach { configuration ->
configuration.resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.squareup.okhttp3') {
details.useVersion(okhttpVersion)
details.because('Check ReactAndroid source compatibility with OkHttp 3')
details.because("Check ReactAndroid source compatibility with OkHttp ${okhttpVersion}")
}
}
}

project.plugins.withId('com.android.library') {
project.tasks.register('verifyOkHttp3Compatibility') { task ->
project.tasks.register('verifyOkHttpCompatibility') { task ->
task.group = 'verification'
task.description = 'Compiles and tests ReactAndroid against OkHttp 3.14.9.'
task.description = "Compiles and tests ReactAndroid against OkHttp ${okhttpVersion}."
task.dependsOn('testDebugUnitTest')
task.doLast {
[
Expand All @@ -39,13 +47,15 @@ gradle.beforeProject { project ->
'debugUnitTestRuntimeClasspath',
].each { name ->
def configuration = project.configurations.getByName(name)
def modules = configuration.incoming.resolutionResult.allComponents
def components = configuration.incoming.resolutionResult.allComponents
.collect { it.id }
.findAll { it instanceof ModuleComponentIdentifier && it.group == 'com.squareup.okhttp3' }
.findAll { it instanceof ModuleComponentIdentifier }
def modules = components.findAll { it.group == 'com.squareup.okhttp3' }
if (modules.isEmpty() || modules.any { it.version != okhttpVersion }) {
throw new GradleException("Expected OkHttp ${okhttpVersion} on ${project.path}:${name}, found: ${modules}")
}
project.logger.lifecycle("Verified ${project.path}:${name}: ${modules}")
def okio = components.findAll { it.group == 'com.squareup.okio' }
project.logger.lifecycle("Verified ${project.path}:${name}: ${modules} with ${okio}")
}
}
}
Expand Down
18 changes: 13 additions & 5 deletions .github/workflows/test-android.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,14 @@ jobs:
skip-apple-prebuilts: true
artifact-suffix: -android

test_okhttp3:
test_okhttp:
runs-on: 8-core-ubuntu
strategy:
fail-fast: false
matrix:
# OkHttp 3 for downstream builds from source, OkHttp 5 for apps that
# depend on it.
okhttp: ['3.14.9', '5.5.1']
container:
image: reactnativecommunity/react-native-android:latest
env:
Expand All @@ -72,15 +78,17 @@ jobs:
uses: ./.github/actions/setup-gradle
with:
cache-encryption-key: ${{ secrets.GRADLE_CACHE_ENCRYPTION_KEY }}
- name: Compile and test ReactAndroid with OkHttp 3.14.9
- name: Compile and test ReactAndroid with OkHttp ${{ matrix.okhttp }}
run: |
./gradlew --init-script .github/workflow-scripts/okhttp3-compat.gradle \
:packages:react-native:ReactAndroid:verifyOkHttp3Compatibility
./gradlew --init-script .github/workflow-scripts/okhttp-compat.gradle \
-PokhttpCompatVersion=${{ matrix.okhttp }} \
-PenableWarningsAsErrors=true \
:packages:react-native:ReactAndroid:verifyOkHttpCompatibility
- name: Upload test results
if: ${{ always() }}
uses: ./.github/actions/upload-artifact
with:
name: android-okhttp3-results
name: android-okhttp-${{ matrix.okhttp }}-results
path: packages/react-native/ReactAndroid/build/reports/tests/testDebugUnitTest/
if-no-files-found: ignore

Expand Down
8 changes: 5 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ The formatting command uses pinned npm packages for Kotlin and Java and installs

## Android networking compatibility

- Keep shared Android Java and Kotlin sources, including devsupport code, source-compatible with OkHttp 3.14.9. Downstream consumers build React Native from source with OkHttp 3 even when the OSS build and tests select a newer version.
- Use APIs available in both OkHttp 3 and the version configured in this repository. Avoid APIs and Kotlin extensions introduced in newer major versions, such as `okhttp3.HttpUrl.Companion.toHttpUrlOrNull`; use compatible APIs such as `Request.Builder().url(...)` for URL validation. The `okhttp3` package name is also used by newer major versions and does not establish compatibility.
- When introducing or changing OkHttp usage, compile the affected sources against OkHttp 3.14.9 and run the relevant tests with the repository's configured version. Passing tests with a newer OkHttp version does not verify OkHttp 3 source compatibility. Report the selected versions, exact commands and results in the PR test plan, and state any compatibility check you could not run.
- Keep shared Android Java and Kotlin sources, including devsupport code, source-compatible with OkHttp 3.14.9 and OkHttp 5. Downstream consumers build React Native from source with OkHttp 3 even when the OSS build and tests select a newer version, and apps that depend on OkHttp 5 run React Native with it.
- Use APIs available in OkHttp 3, OkHttp 5 and the version configured in this repository. Avoid APIs and Kotlin extensions introduced after OkHttp 3, such as `okhttp3.HttpUrl.Companion.toHttpUrlOrNull`; use compatible APIs such as `Request.Builder().url(...)` for URL validation. The `okhttp3` package name is also used by newer major versions and does not establish compatibility.
- `Response.body()` is declared nullable before OkHttp 5 and non-null from OkHttp 5 on. Before comparing it with null or calling it with `?.`, assign it to an explicitly nullable value, such as `val body: ResponseBody? = response.body()`, so the code compiles without warnings on every version.
- Don't use `okhttp-urlconnection` (`okhttp3.JavaNetCookieJar`, `okhttp3.JavaNetAuthenticator`) in main sources. Each `JavaNetCookieJar` release calls internals of its own OkHttp major version, and 4.9.2's crashes apps that depend on OkHttp 5 (#52945). To store cookies in a `CookieHandler`, use `CookieHandlerCookieJar`. ReactAndroid still declares `okhttp-urlconnection` as an `api` dependency for code that uses it through React Native, and `CookieHandlerCookieJarTest` uses it as its reference implementation.
- When introducing or changing OkHttp usage, compile the affected sources and run the relevant tests with each OkHttp version in the `test_okhttp` matrix in `.github/workflows/test-android.yml`, and with the repository's configured version. `./gradlew --init-script .github/workflow-scripts/okhttp-compat.gradle -PokhttpCompatVersion=3.14.9 -PenableWarningsAsErrors=true :packages:react-native:ReactAndroid:verifyOkHttpCompatibility` compiles ReactAndroid and runs its JVM tests with the given version. Passing tests with a newer OkHttp version does not verify OkHttp 3 source compatibility. Report the selected versions, exact commands and results in the PR test plan, and state any compatibility check you could not run.

## Verification: Running RNTester

Expand Down
2 changes: 2 additions & 0 deletions packages/react-native/ReactAndroid/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,8 @@ dependencies {
api(libs.yoga.proguard.annotations)

api(libs.jsr305)
// Publish okhttp-urlconnection for code that uses JavaNetCookieJar or
// JavaNetAuthenticator through react-android. React Native itself doesn't use it.
api(libs.okhttp3.urlconnection)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this can be made non-breaking as apps can declare in their .gradle files that they don't intend to consume this api dependency from react-native.

@ide ide Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ReactAndroid now keeps okhttp-urlconnection as an api dependency, so the change is no longer breaking, and the [BREAKING] changelog entry is gone.
An app on OkHttp 5 needs to exclude it only if its code or a keep rule retains JavaNetCookieJar.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An app on OkHttp 5 needs to exclude it only if its code or a keep rule retains JavaNetCookieJar.

We probably need a page on the website explaining how to do this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a section to the Networking page: react/react-native-website#5363

api(libs.okhttp3)
api(libs.okio)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okio.BufferedSource
import okio.Okio
import org.json.JSONException
Expand Down Expand Up @@ -130,7 +131,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
// In case the server doesn't support multipart/mixed responses, fallback to
// normal
// download.
val body = resp.body()
val body: ResponseBody? = resp.body() // Nullable before OkHttp 5
if (body != null) {
body.use {
processBundleResult(
Expand Down Expand Up @@ -169,7 +170,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
bundleInfo: BundleInfo?,
callback: DevBundleDownloadListener,
) {
val responseBody = response.body()
val responseBody: ResponseBody? = response.body() // Nullable before OkHttp 5
if (responseBody == null) {
callback.onFailure(
DebugServerException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Okio

/**
Expand Down Expand Up @@ -331,12 +332,11 @@ public open class DevServerHelper(

try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful || response.body() == null) {
val body: ResponseBody? = response.body() // Nullable before OkHttp 5
if (!response.isSuccessful || body == null) {
return null
}
Okio.sink(outputFile).use { output ->
Okio.buffer(response.body()?.source()!!).readAll(output)
}
Okio.sink(outputFile).use { output -> Okio.buffer(body.source()).readAll(output) }
return outputFile
}
} catch (e: Exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody

/** Use this class to check if the JavaScript packager is running on the provided host. */
internal class PackagerStatusCheck(private val client: OkHttpClient) {
Expand Down Expand Up @@ -51,7 +52,7 @@ internal class PackagerStatusCheck(private val client: OkHttpClient) {
callback.onPackagerStatusFetched(false)
return
}
val body = response.body()
val body: ResponseBody? = response.body() // Nullable before OkHttp 5
if (body == null) {
FLog.e(
ReactConstants.TAG,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody

internal object InspectorNetworkHelper {

Expand Down Expand Up @@ -52,7 +53,8 @@ internal object InspectorNetworkHelper {
listener.onHeaders(response.code(), headersMap)

try {
response.body().use { responseBody ->
val body: ResponseBody? = response.body() // Nullable before OkHttp 5
body.use { responseBody ->
if (responseBody != null) {
val inputStream = responseBody.byteStream()
val chunkSize = 8 * 1024 // 8Kb
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.common.ReactConstants
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.modules.common.ModuleDataCleaner
import com.facebook.react.modules.network.CookieHandlerCookieJar
import com.facebook.react.modules.network.CookieJarContainer
import com.facebook.react.modules.network.ForwardingCookieHandler
import com.facebook.react.modules.network.OkHttpClientProvider
import com.facebook.react.turbomodule.core.interfaces.TurboModule
import okhttp3.JavaNetCookieJar

/**
* Module to initialize the Fresco library.
Expand Down Expand Up @@ -162,7 +162,7 @@ constructor(
val container = client.cookieJar() as CookieJarContainer

val handler = ForwardingCookieHandler()
container.setCookieJar(JavaNetCookieJar(handler))
container.setCookieJar(CookieHandlerCookieJar(handler))
val builder =
OkHttpImagePipelineConfigFactory.newBuilder(context.applicationContext, client)
.setNetworkFetcher(ReactOkHttpNetworkFetcher(client))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

@file:Suppress("DEPRECATION_ERROR") // Conflicting okhttp versions

package com.facebook.react.modules.network

import com.facebook.common.logging.FLog
import com.facebook.react.common.ReactConstants
import java.io.IOException
import java.net.CookieHandler
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

/**
* Stores OkHttp's cookies in a [CookieHandler], as `JavaNetCookieJar` from `okhttp-urlconnection`
* does, through API that OkHttp 3, 4 and 5 share. Each `JavaNetCookieJar` release calls internals
* of its own OkHttp major version: 4.9.2's throws `NoClassDefFoundError` on OkHttp 5.
*/
internal class CookieHandlerCookieJar(private val cookieHandler: CookieHandler) : CookieJar {

override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
val headers = mapOf("Set-Cookie" to cookies.map { toSetCookieHeader(it) })
try {
cookieHandler.put(url.uri(), headers)
} catch (e: IOException) {
FLog.w(ReactConstants.TAG, "Saving cookies failed for ${url.redact()}", e)
}
}

override fun loadForRequest(url: HttpUrl): List<Cookie> {
val headers =
try {
cookieHandler.get(url.uri(), emptyMap())
} catch (e: IOException) {
FLog.w(ReactConstants.TAG, "Loading cookies failed for ${url.redact()}", e)
return emptyList()
}
return headers
.filterKeys {
it.equals("Cookie", ignoreCase = true) || it.equals("Cookie2", ignoreCase = true)
}
.values
.flatMap { values -> values.flatMap { decodeCookieHeader(url, it) } }
}

private companion object {
private const val DOMAIN_ATTRIBUTE = "; domain="

/**
* [Cookie.toString], with a leading dot on the domain of a cookie that isn't host-only.
* Handlers that follow RFC 2965, such as [java.net.CookieManager], need the dot to match
* `www.example.com` to `example.com`.
*/
fun toSetCookieHeader(cookie: Cookie): String {
val header = cookie.toString()
if (cookie.hostOnly()) {
return header
}
// Search after "name=value", so a value can't be mistaken for the attribute.
val attribute =
header.indexOf(DOMAIN_ATTRIBUTE, cookie.name().length + 1 + cookie.value().length)
if (attribute < 0) {
return header
}
val domain = attribute + DOMAIN_ATTRIBUTE.length
return header.substring(0, domain) + "." + header.substring(domain)
}

/**
* Splits a `Cookie` request header into cookies. [Cookie.parse] can't: it reads one
* `Set-Cookie` value.
*/
fun decodeCookieHeader(url: HttpUrl, header: String): List<Cookie> {
val result = mutableListOf<Cookie>()
var pos = 0
while (pos < header.length) {
val pairEnd =
header.indexOfAny(PAIR_DELIMITERS, pos).let { if (it < 0) header.length else it }
val equalsSign =
header.indexOf('=', pos).let { if (it < 0 || it > pairEnd) pairEnd else it }
val name = header.substring(pos, equalsSign).trim(::isAsciiWhitespace)
pos = pairEnd + 1
if (name.startsWith("$")) {
continue // An attribute such as $Path, not a cookie.
}
var value =
if (equalsSign < pairEnd)
header.substring(equalsSign + 1, pairEnd).trim(::isAsciiWhitespace)
else ""
if (value.length >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length - 1)
}
// Cookie.Builder rejects surrounding whitespace, which unquoting can leave, as in "abc ".
value = value.trim()
try {
// Cookie.Builder accepts characters (such as non-ASCII, DEL, and control characters other
// than tab) that OkHttp rejects when building the Cookie request header, and it rejects a
// name or value that its own trim would change (which differs across OkHttp versions).
// Uncaught, either IllegalArgumentException fails the request, and OkHttp rethrows it on
// its dispatcher thread, which crashes the app.
require(name.all(::isValidHeaderCharacter) && value.all(::isValidHeaderCharacter)) {
"Invalid request header characters"
}
result.add(Cookie.Builder().name(name).value(value).domain(url.host()).build())
} catch (_: IllegalArgumentException) {
// Omit cookie contents, exception message, and stack trace: a stored cookie is rejected
// again on every request to its host.
FLog.w(ReactConstants.TAG, "Skipped a cookie OkHttp rejects for ${url.redact()}")
}
}
return result
}

private val PAIR_DELIMITERS = charArrayOf(';', ',')

private fun isAsciiWhitespace(c: Char): Boolean =
c == ' ' || c == '\t' || c == '\n' || c == '\u000C' || c == '\r'

private fun isValidHeaderCharacter(c: Char): Boolean = c == '\t' || c in ' '..'~'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -251,19 +251,20 @@ internal object NetworkEventUtil {
// Unwrap ProgressRequestBody
val body = (requestBody as? ProgressRequestBody)?.innerBody() ?: requestBody

// Check each part of a MultipartBody before checking the whole body: OkHttp 5
// reports a multipart body as one-shot when any part is, and OkHttp 3 and 4
// never do. Reading a one-shot part here would drain the underlying stream and
// cause the real request to fail.
if (body is MultipartBody && body.parts().any { it.body().isOneShot() }) {
return previewMultipartWithBinaryParts(body)
}

if (body.isOneShot()) {
// Reading would drain the underlying stream and break the real upload,
// so fall back to a placeholder that includes the byte count when known
return binaryPartLabel(body)
}

// MultipartBody does not propagate isOneShot() from its parts, so check each
// part explicitly. Reading a one-shot part here would drain the underlying
// stream and cause the real request to fail.
if (body is MultipartBody && body.parts().any { it.body().isOneShot() }) {
return previewMultipartWithBinaryParts(body)
}

return try {
val buffer = Buffer()
body.writeTo(buffer)
Expand Down
Loading
Loading