or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

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

index.mddocs/

OkHttp URLConnection

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.

Package Information

  • Package Name: okhttp-urlconnection
  • Package Type: maven
  • Language: Kotlin with Java compatibility
  • Group ID: com.squareup.okhttp3
  • Artifact ID: okhttp-urlconnection
  • Installation: implementation("com.squareup.okhttp3:okhttp-urlconnection:4.12.0")

Core Imports

import okhttp3.JavaNetCookieJar
import okhttp3.JavaNetAuthenticator
import java.net.CookieHandler
import java.net.Authenticator

For Java:

import okhttp3.JavaNetCookieJar;
import okhttp3.JavaNetAuthenticator;
import java.net.CookieHandler;
import java.net.Authenticator;

Basic Usage

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.JavaNetCookieJar
import okhttp3.JavaNetAuthenticator
import java.net.CookieHandler
import java.net.Authenticator

// Setup with existing java.net components
val client = OkHttpClient.Builder()
    // Use existing CookieHandler for cookie management
    .cookieJar(JavaNetCookieJar(CookieHandler.getDefault()))
    // Use existing Authenticator for authentication
    .authenticator(JavaNetAuthenticator())
    .build()

// The client now integrates with system cookie and authentication handlers
val request = Request.Builder()
    .url("https://api.example.com/data")
    .build()

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

Architecture

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

  • Legacy java.net Integration: Maintains compatibility with existing java.net-based systems
  • OkHttp Delegation: Leverages OkHttp's advanced HTTP implementation while preserving existing authentication and cookie infrastructure
  • Drop-in Replacement: Allows migration from HttpURLConnection to OkHttp without changing authentication or cookie management code
  • 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

Capabilities

Cookie Management Integration

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

/**
 * A cookie jar that delegates to a java.net.CookieHandler
 * @param cookieHandler The CookieHandler to delegate cookie operations to
 */
class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
    
    /**
     * Saves cookies from an HTTP response to the underlying CookieHandler
     * @param url The URL for which cookies are being saved
     * @param cookies List of cookies to save
     */
    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>): Unit
    
    /**
     * Loads cookies for an HTTP request from the underlying CookieHandler
     * @param url The URL for which cookies are being loaded
     * @return List of cookies applicable to the request
     */
    override fun loadForRequest(url: HttpUrl): List<Cookie>
}

Usage Examples:

import okhttp3.JavaNetCookieJar
import java.net.CookieHandler
import java.net.CookieManager
import java.net.CookiePolicy

// Using default system cookie handler
val cookieJar = JavaNetCookieJar(CookieHandler.getDefault())

// Using custom cookie manager
val cookieManager = CookieManager()
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
val customCookieJar = JavaNetCookieJar(cookieManager)

// Apply to OkHttp client
val client = OkHttpClient.Builder()
    .cookieJar(cookieJar)
    .build()

Authentication Integration

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.

/**
 * Adapts java.net.Authenticator to okhttp3.Authenticator for seamless authentication integration.
 * This is a simple wrapper that delegates to OkHttp's JAVA_NET_AUTHENTICATOR.
 */
class JavaNetAuthenticator : okhttp3.Authenticator {
    
    /**
     * Handles authentication challenges by delegating to OkHttp's built-in java.net.Authenticator support.
     * Only supports Basic authentication schemes.
     * @param route The network route for the request (nullable)
     * @param response The HTTP response containing the authentication challenge
     * @return A new Request with authentication credentials, or null if authentication fails
     * @throws IOException If authentication process encounters an error
     */
    @Throws(IOException::class)
    override fun authenticate(route: Route?, response: Response): Request?
}

Usage Examples:

import okhttp3.JavaNetAuthenticator
import okhttp3.OkHttpClient
import java.net.Authenticator
import java.net.PasswordAuthentication

// Setup system authenticator (typically done once per application)
Authenticator.setDefault(object : Authenticator() {
    override fun getPasswordAuthentication(): PasswordAuthentication {
        return PasswordAuthentication("username", "password".toCharArray())
    }
})

// Use with OkHttp client - delegates to OkHttp's built-in java.net integration
val client = OkHttpClient.Builder()
    .authenticator(JavaNetAuthenticator())
    .build()

// For proxy authentication - also delegates to built-in implementation
val clientWithProxyAuth = OkHttpClient.Builder()
    .proxyAuthenticator(JavaNetAuthenticator())
    .build()

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

Types

Core OkHttp Types

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

/**
 * HTTP URL representation used throughout OkHttp
 */
class HttpUrl {
    val scheme: String
    val host: String
    val port: Int
    fun toUri(): java.net.URI
}

/**
 * HTTP cookie representation in OkHttp
 */
class Cookie {
    val name: String
    val value: String
    val domain: String
    val path: String
    val secure: Boolean
    val httpOnly: Boolean
    
    class Builder {
        fun name(name: String): Builder
        fun value(value: String): Builder
        fun domain(domain: String): Builder
        fun build(): Cookie
    }
}

/**
 * Network route information
 */
class Route {
    val address: Address
    val proxy: java.net.Proxy
}

/**
 * HTTP request representation
 */
class Request {
    val url: HttpUrl
    val method: String
    val headers: Headers
    val body: RequestBody?
}

/**
 * HTTP response representation
 */
class Response {
    val request: Request
    val code: Int
    val message: String
    val headers: Headers
    val body: ResponseBody?
}

/**
 * Cookie storage and retrieval interface
 */
interface CookieJar {
    fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>)
    fun loadForRequest(url: HttpUrl): List<Cookie>
}

/**
 * Authentication challenge handler interface
 */
interface Authenticator {
    @Throws(IOException::class)
    fun authenticate(route: Route?, response: Response): Request?
}

Java Standard Library Types

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

/**
 * Java's standard cookie handling interface
 */
abstract class java.net.CookieHandler {
    abstract fun get(uri: java.net.URI, requestHeaders: Map<String, List<String>>): Map<String, List<String>>
    abstract fun put(uri: java.net.URI, responseHeaders: Map<String, List<String>>)
}

/**
 * Java's standard authentication interface
 */
abstract class java.net.Authenticator {
    abstract fun getPasswordAuthentication(): java.net.PasswordAuthentication?
}

Error Handling

Both integration classes handle errors gracefully:

JavaNetCookieJar Error Handling

  • IOException during cookie operations: Logs warnings but continues operation
  • Malformed cookie headers: Silently skips invalid cookies
  • Missing CookieHandler: Throws IllegalArgumentException on construction

JavaNetAuthenticator Error Handling

  • IOException during authentication: Propagated to caller (delegated to internal implementation)
  • Authentication failure: Returns null Request
  • Unsupported authentication schemes: Returns null for non-Basic authentication schemes (handled by internal implementation)
  • No system authenticator: Uses default java.net.Authenticator behavior (handled by internal implementation)

Common Error Scenarios:

// Handle authentication failures
val response = client.newCall(request).execute()
if (response.code == 401) {
    // Authentication failed - check Authenticator configuration
    println("Authentication required but failed")
}

// Handle cookie persistence issues
// JavaNetCookieJar will log warnings for cookie save/load failures
// but will not throw exceptions - check logs for cookie-related issues