okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

How to cleanly pin a network on Android

Open yschimke opened this issue 1 year ago • 5 comments

WorkManager provides a required network for scheduled jobs with network constraints

https://developer.android.com/reference/androidx/work/WorkerParameters#getNetwork()

Using this specific network is possible with a custom Dns and SocketFactory. However the naive implementation would probably result in defeating connection pooling in some cases.

Is there a supported pattern for this, if Dns and SocketFactory both support equality checks, would pooling be correctly retained?

cc @swankjesse

yschimke avatar Mar 15 '24 15:03 yschimke

How about this:

/**
 * Returns a DNS that uses this network’s `getAllByName` function.
 * 
 * Different objects returned from this will be equal if their networks are equal.
 */
val Network.dns: Dns

And maybe also this:

/**
 * Returns a client that uses [network] for its socket factory and DNS. The
 * client will only be able to make calls to hosts that are reachable on [network].
 */
fun OkHttpClient.Builder.network(network: Network)

Plus @JvmName stuff to make the Java APIs reasonable.

Do we need to hide these in the okhttp-android module? It’d be nice to do it in the main okhttp module.

swankjesse avatar Apr 14 '24 18:04 swankjesse

@swankjesse for discussion in https://github.com/square/okhttp/pull/8376, I think I want to move away from recreating the OkHttpClient instance, and instead configure Dns, SocketFactory and Address matcher? that listen for a Request tag (NetworkPin) that callers or interceptors set.

yschimke avatar Apr 20 '24 11:04 yschimke

@swankjesse for discussion in #8376, I think I want to move away from recreating the OkHttpClient instance, and instead configure Dns, SocketFactory and Address matcher? that listen for a Request tag (NetworkPin) that callers or interceptors set. 对于 #8376 中的讨论,我想我不想重新创建 OkHttpClient 实例,而是配置 Dns、SocketFactory 和地址匹配器?侦听调用者或拦截器设置的请求标记 (NetworkPin)。

Hello, have you solved this problem?

appdev avatar May 08 '24 03:05 appdev

No, the approach requires a new client.

yschimke avatar May 08 '24 07:05 yschimke

in progress PR I'll come back to in https://github.com/square/okhttp/pull/8376

yschimke avatar Jul 26 '25 13:07 yschimke