or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/maven-com-squareup-okhttp3--okhttp-urlconnection

This package integrates OkHttp with Authenticator and CookieHandler from java.net

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup.okhttp3/okhttp-urlconnection@4.12.x

To install, run

npx @tessl/cli install tessl/maven-com-squareup-okhttp3--okhttp-urlconnection@4.12.0

0

# OkHttp URLConnection

1

2

OkHttp URLConnection provides integration between OkHttp HTTP client and Java's standard networking APIs (java.net). It consists of two bridge adapter classes that allow OkHttp to work seamlessly with existing java.net-based cookie management and authentication systems.

3

4

## Package Information

5

6

- **Package Name**: okhttp-urlconnection

7

- **Package Type**: maven

8

- **Language**: Kotlin with Java compatibility

9

- **Group ID**: com.squareup.okhttp3

10

- **Artifact ID**: okhttp-urlconnection

11

- **Installation**: `implementation("com.squareup.okhttp3:okhttp-urlconnection:4.12.0")`

12

13

## Core Imports

14

15

```kotlin

16

import okhttp3.JavaNetCookieJar

17

import okhttp3.JavaNetAuthenticator

18

import java.net.CookieHandler

19

import java.net.Authenticator

20

```

21

22

For Java:

23

24

```java

25

import okhttp3.JavaNetCookieJar;

26

import okhttp3.JavaNetAuthenticator;

27

import java.net.CookieHandler;

28

import java.net.Authenticator;

29

```

30

31

## Basic Usage

32

33

```kotlin

34

import okhttp3.OkHttpClient

35

import okhttp3.Request

36

import okhttp3.JavaNetCookieJar

37

import okhttp3.JavaNetAuthenticator

38

import java.net.CookieHandler

39

import java.net.Authenticator

40

41

// Setup with existing java.net components

42

val client = OkHttpClient.Builder()

43

// Use existing CookieHandler for cookie management

44

.cookieJar(JavaNetCookieJar(CookieHandler.getDefault()))

45

// Use existing Authenticator for authentication

46

.authenticator(JavaNetAuthenticator())

47

.build()

48

49

// The client now integrates with system cookie and authentication handlers

50

val request = Request.Builder()

51

.url("https://api.example.com/data")

52

.build()

53

54

val response = client.newCall(request).execute()

55

```

56

57

## Architecture

58

59

OkHttp URLConnection is designed as a bridge between two HTTP client ecosystems:

60

61

- **Legacy java.net Integration**: Maintains compatibility with existing java.net-based systems

62

- **OkHttp Delegation**: Leverages OkHttp's advanced HTTP implementation while preserving existing authentication and cookie infrastructure

63

- **Drop-in Replacement**: Allows migration from HttpURLConnection to OkHttp without changing authentication or cookie management code

64

- **Adapter Pattern**: `JavaNetCookieJar` implements the adapter pattern by delegating to java.net implementations, while `JavaNetAuthenticator` is a simple wrapper that delegates to OkHttp's built-in `JAVA_NET_AUTHENTICATOR` implementation

65

66

## Capabilities

67

68

### Cookie Management Integration

69

70

Bridges OkHttp's cookie system with Java's standard CookieHandler, enabling seamless cookie management across HTTP clients.

71

72

```kotlin { .api }

73

/**

74

* A cookie jar that delegates to a java.net.CookieHandler

75

* @param cookieHandler The CookieHandler to delegate cookie operations to

76

*/

77

class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {

78

79

/**

80

* Saves cookies from an HTTP response to the underlying CookieHandler

81

* @param url The URL for which cookies are being saved

82

* @param cookies List of cookies to save

83

*/

84

override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>): Unit

85

86

/**

87

* Loads cookies for an HTTP request from the underlying CookieHandler

88

* @param url The URL for which cookies are being loaded

89

* @return List of cookies applicable to the request

90

*/

91

override fun loadForRequest(url: HttpUrl): List<Cookie>

92

}

93

```

94

95

**Usage Examples:**

96

97

```kotlin

98

import okhttp3.JavaNetCookieJar

99

import java.net.CookieHandler

100

import java.net.CookieManager

101

import java.net.CookiePolicy

102

103

// Using default system cookie handler

104

val cookieJar = JavaNetCookieJar(CookieHandler.getDefault())

105

106

// Using custom cookie manager

107

val cookieManager = CookieManager()

108

cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)

109

val customCookieJar = JavaNetCookieJar(cookieManager)

110

111

// Apply to OkHttp client

112

val client = OkHttpClient.Builder()

113

.cookieJar(cookieJar)

114

.build()

115

```

116

117

### Authentication Integration

118

119

Provides a simple wrapper that delegates to OkHttp's built-in Java.net authenticator integration. This class simply delegates to the main OkHttp authenticator implementation.

120

121

```kotlin { .api }

122

/**

123

* Adapts java.net.Authenticator to okhttp3.Authenticator for seamless authentication integration.

124

* This is a simple wrapper that delegates to OkHttp's JAVA_NET_AUTHENTICATOR.

125

*/

126

class JavaNetAuthenticator : okhttp3.Authenticator {

127

128

/**

129

* Handles authentication challenges by delegating to OkHttp's built-in java.net.Authenticator support.

130

* Only supports Basic authentication schemes.

131

* @param route The network route for the request (nullable)

132

* @param response The HTTP response containing the authentication challenge

133

* @return A new Request with authentication credentials, or null if authentication fails

134

* @throws IOException If authentication process encounters an error

135

*/

136

@Throws(IOException::class)

137

override fun authenticate(route: Route?, response: Response): Request?

138

}

139

```

140

141

**Usage Examples:**

142

143

```kotlin

144

import okhttp3.JavaNetAuthenticator

145

import okhttp3.OkHttpClient

146

import java.net.Authenticator

147

import java.net.PasswordAuthentication

148

149

// Setup system authenticator (typically done once per application)

150

Authenticator.setDefault(object : Authenticator() {

151

override fun getPasswordAuthentication(): PasswordAuthentication {

152

return PasswordAuthentication("username", "password".toCharArray())

153

}

154

})

155

156

// Use with OkHttp client - delegates to OkHttp's built-in java.net integration

157

val client = OkHttpClient.Builder()

158

.authenticator(JavaNetAuthenticator())

159

.build()

160

161

// For proxy authentication - also delegates to built-in implementation

162

val clientWithProxyAuth = OkHttpClient.Builder()

163

.proxyAuthenticator(JavaNetAuthenticator())

164

.build()

165

```

166

167

**Note:** `JavaNetAuthenticator` only supports Basic authentication schemes. Other authentication schemes (Digest, NTLM, etc.) will be ignored and return null.

168

169

## Types

170

171

### Core OkHttp Types

172

173

These types are provided by the main OkHttp library and are used by the integration classes:

174

175

```kotlin { .api }

176

/**

177

* HTTP URL representation used throughout OkHttp

178

*/

179

class HttpUrl {

180

val scheme: String

181

val host: String

182

val port: Int

183

fun toUri(): java.net.URI

184

}

185

186

/**

187

* HTTP cookie representation in OkHttp

188

*/

189

class Cookie {

190

val name: String

191

val value: String

192

val domain: String

193

val path: String

194

val secure: Boolean

195

val httpOnly: Boolean

196

197

class Builder {

198

fun name(name: String): Builder

199

fun value(value: String): Builder

200

fun domain(domain: String): Builder

201

fun build(): Cookie

202

}

203

}

204

205

/**

206

* Network route information

207

*/

208

class Route {

209

val address: Address

210

val proxy: java.net.Proxy

211

}

212

213

/**

214

* HTTP request representation

215

*/

216

class Request {

217

val url: HttpUrl

218

val method: String

219

val headers: Headers

220

val body: RequestBody?

221

}

222

223

/**

224

* HTTP response representation

225

*/

226

class Response {

227

val request: Request

228

val code: Int

229

val message: String

230

val headers: Headers

231

val body: ResponseBody?

232

}

233

234

/**

235

* Cookie storage and retrieval interface

236

*/

237

interface CookieJar {

238

fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>)

239

fun loadForRequest(url: HttpUrl): List<Cookie>

240

}

241

242

/**

243

* Authentication challenge handler interface

244

*/

245

interface Authenticator {

246

@Throws(IOException::class)

247

fun authenticate(route: Route?, response: Response): Request?

248

}

249

```

250

251

### Java Standard Library Types

252

253

These are the standard Java networking types that the integration classes work with:

254

255

```kotlin { .api }

256

/**

257

* Java's standard cookie handling interface

258

*/

259

abstract class java.net.CookieHandler {

260

abstract fun get(uri: java.net.URI, requestHeaders: Map<String, List<String>>): Map<String, List<String>>

261

abstract fun put(uri: java.net.URI, responseHeaders: Map<String, List<String>>)

262

}

263

264

/**

265

* Java's standard authentication interface

266

*/

267

abstract class java.net.Authenticator {

268

abstract fun getPasswordAuthentication(): java.net.PasswordAuthentication?

269

}

270

```

271

272

## Error Handling

273

274

Both integration classes handle errors gracefully:

275

276

### JavaNetCookieJar Error Handling

277

278

- **IOException during cookie operations**: Logs warnings but continues operation

279

- **Malformed cookie headers**: Silently skips invalid cookies

280

- **Missing CookieHandler**: Throws IllegalArgumentException on construction

281

282

### JavaNetAuthenticator Error Handling

283

284

- **IOException during authentication**: Propagated to caller (delegated to internal implementation)

285

- **Authentication failure**: Returns null Request

286

- **Unsupported authentication schemes**: Returns null for non-Basic authentication schemes (handled by internal implementation)

287

- **No system authenticator**: Uses default java.net.Authenticator behavior (handled by internal implementation)

288

289

**Common Error Scenarios:**

290

291

```kotlin

292

// Handle authentication failures

293

val response = client.newCall(request).execute()

294

if (response.code == 401) {

295

// Authentication failed - check Authenticator configuration

296

println("Authentication required but failed")

297

}

298

299

// Handle cookie persistence issues

300

// JavaNetCookieJar will log warnings for cookie save/load failures

301

// but will not throw exceptions - check logs for cookie-related issues

302

```