/java-skills:okhttp5from java-skills
Reference for OkHttp 5.x HTTP client for Java/JVM 8+ and Android 5+. Covers HTTP/2, connection pooling, interceptors, caching, WebSockets, SSE, TLS, MockWebServer, and GraalVM Native Image.
Ships in java-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
OkHttp is an efficient HTTP client by default: HTTP/2 support, connection pooling, transparent GZIP, and response caching. It silently recovers from common connection problems and attempts alternate addresses when the first connect fails.
All authoritative information is on the official OkHttp site:
RFC Standards followed by OkHttp:
okhttp-jvm artifact (not okhttp)Should not use OkHttp for:
Use this skill when the user needs to:
Key changes in OkHttp 5.x:
okhttp-jvm for Maven)mockwebserver3), no JUnit 4 dependency, immutable APIokcurl module for examplemodule-info.java files (5.2+)okhttp-zstd module for Zstandard compressionGradle:
dependencies {
implementation(platform("com.squareup.okhttp3:okhttp-bom:5.4.0"))
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
}
Maven (JVM — must use okhttp-jvm):
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-bom</artifactId>
<version>5.4.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-jvm</artifactId>
</dependency>
</dependencies>
Minimal GET:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://api.example.com/users").build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
Minimal POST JSON:
RequestBody body = RequestBody.create("{\"name\":\"Alice\"}", MediaType.get("application/json"));
Request request = new Request.Builder().url("https://api.example.com/users").post(body).build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
Step 1. Confirm environment — Check Java 8+ or Android 5+, choose Maven (okhttp-jvm) or Gradle (okhttp)
Step 2. Configure OkHttpClient — Set timeouts, connection pool, cache, interceptors, TLS
Step 3. Build Request — Set URL, method, headers, body
Step 4. Execute Call — Synchronous (execute()) or asynchronous (enqueue())
Step 5. Handle Response — Check status, read body, handle errors
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.callTimeout(60, TimeUnit.SECONDS) // Entire call timeout
.connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
.cache(new Cache(new File("cache-dir"), 50L * 1024L * 1024L)) // 50 MiB
.addInterceptor(new LoggingInterceptor()) // Application interceptor
.addNetworkInterceptor(new NetworkInterceptor()) // Network interceptor
.followRedirects(true)
.followSslRedirects(true)
.retryOnConnectionFailure(true)
.build();
Key configuration options:
| Builder Method | Impact | Default |
|---|---|---|
connectTimeout(int, TimeUnit) | TCP connection timeout | 10 seconds |
readTimeout(int, TimeUnit) | Socket read timeout | 10 seconds |
writeTimeout(int, TimeUnit) | Socket write timeout | 10 seconds |
callTimeout(int, TimeUnit) | Entire call timeout (all steps) | no limit |
connectionPool(ConnectionPool) | Connection pool settings | 5 idle, 5 min keepalive |
cache(Cache) | Response cache (off by default) | null |
followRedirects(boolean) | Follow HTTP redirects | true |
followSslRedirects(boolean) | Follow HTTPS↔HTTP redirects | true |
retryOnConnectionFailure(boolean) | Retry on stale connection | true |
dns(Dns) | Custom DNS resolver | System DNS |
proxy(Proxy) | Single proxy | null (direct) |
proxySelector(ProxySelector) | Per-request proxy selection | system default |
authenticator(Authenticator) | HTTP auth challenges | none |
certificatePinner(CertificatePinner) | Certificate pinning | none |
sslSocketFactory(SSLSocketFactory, X509TrustManager) | Custom TLS | platform default |
connectionSpecs(List<ConnectionSpec>) | TLS versions and cipher suites | MODERN_TLS |
eventListenerFactory(EventListener.Factory) | Event monitoring | none |
See references/configuration.md for full reference.
Request building:
Request request = new Request.Builder()
.url("https://api.example.com/users/1")
.header("Authorization", "Bearer token123")
.addHeader("Accept", "application/json")
.get()
.build();
POST with JSON body:
RequestBody body = RequestBody.create(jsonString, MediaType.get("application/json"));
Request request = new Request.Builder()
.url("https://api.example.com/users")
.post(body)
.build();
POST with form data:
RequestBody formBody = new FormBody.Builder()
.add("username", "alice")
.add("password", "secret")
.build();
Multipart upload:
RequestBody fileBody = RequestBody.create(new File("photo.jpg"), MediaType.get("image/jpeg"));
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "My Photo")
.addFormDataPart("photo", "photo.jpg", fileBody)
.build();
See references/calls.md for PUT/DELETE, request/response lifecycle.
Synchronous:
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String body = response.body().string();
int code = response.code();
String contentType = response.header("Content-Type");
}
Asynchronous:
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) { e.printStackTrace(); }
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody body = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(body.string());
}
}
});
See references/calls.md for follow-ups, retries, Dispatcher.
Application interceptor — sees the original request, even for cached responses:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Network interceptor — sees the actual network request (with OkHttp-added headers):
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new LoggingInterceptor())
.build();
Logging interceptor (built-in):
import okhttp3.logging.HttpLoggingInterceptor;
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
See references/interceptors.md for Application vs Network, GzipRequestInterceptor.
Enable cache:
OkHttpClient client = new OkHttpClient.Builder()
.cache(new Cache(new File("cache-dir"), 50L * 1024L * 1024L)) // 50 MiB
.build();
Cache events: CacheHit, CacheMiss, CacheConditionalHit
Prune cache:
cache.evictAll(); // Clear all
Iterator<String> urlIterator = cache.urls();
while (urlIterator.hasNext()) {
if (urlIterator.next().startsWith("https://api.example.com/")) urlIterator.remove();
}
See references/caching.md for eviction, troubleshooting.
OkHttp uses a layered model: URL → Address → Route → Connection
Fast Fallback (Happy Eyeballs, 5.0+):
See references/connections.md for connection pooling, Fast Fallback details.
4 built-in ConnectionSpecs:
RESTRICTED_TLS — strictest, for complianceMODERN_TLS — default, secure modern serversCOMPATIBLE_TLS — older but still secure serversCLEARTEXT — for http:// URLs onlyFallback configuration:
OkHttpClient client = new OkHttpClient.Builder()
.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
.build();
Certificate pinning:
OkHttpClient client = new OkHttpClient.Builder()
.certificatePinner(
new CertificatePinner.Builder()
.add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
.build())
.build();
See references/https.md for TLS debugging, custom TrustManager, cipher suites.
| Pattern | Description |
|---|---|
| Synchronous GET | client.newCall(request).execute() |
| Asynchronous GET | client.newCall(request).enqueue(callback) |
| POST String/File | RequestBody.create(content, mediaType) |
| POST Form | FormBody.Builder().add(name, value) |
| Multipart Upload | MultipartBody.Builder().addFormDataPart(...) |
| Per-call Config | client.newBuilder().readTimeout(...).build() |
| Authentication | OkHttpClient.Builder().authenticator(...) |
| Cancellation | call.cancel() |
| Upload Progress | Wrap RequestBody with ForwardingSink |
See references/recipes.md for complete code examples.
ConnectionSpec.MODERN_TLS (default); fall back to COMPATIBLE_TLS for older serversCertificatePinner to restrict trusted CAsSee references/security.md for TLS history and provider configuration.
Event sequence (successful call):
callStart → dnsStart → dnsEnd → connectStart → secureConnectStart → secureConnectEnd → connectEnd → connectionAcquired → requestHeadersStart → requestHeadersEnd → responseHeadersStart → responseHeadersEnd → responseBodyStart → responseBodyEnd → connectionReleased → callEnd
Pooled connection (skips connect events):
callStart → connectionAcquired → requestHeadersStart → requestHeadersEnd → responseHeadersStart → responseHeadersEnd → responseBodyStart → responseBodyEnd → connectionReleased → callEnd
Factory for concurrent calls:
EventListener.Factory factory = new EventListener.Factory() {
@Override public EventListener create(Call call) {
return new TimingEventListener();
}
};
See references/events.md for complete EventListener code, failure/retry events, 10% sampling.
Basic usage:
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setBody("Hello World!"));
server.start();
Request request = new Request.Builder().url(server.url("/")).build();
try (Response response = client.newCall(request).execute()) {
assertEquals("Hello World!", response.body().string());
}
server.shutdown();
Maven (use mockwebserver3):
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver3</artifactId>
<scope>test</scope>
</dependency>
See references/calls.md for RecordedRequest verification.
| Error | Cause | Fix |
|---|---|---|
java.lang.NoClassDefFoundError: kotlin/jvm/internal/... | Missing Kotlin stdlib | OkHttp 5.x is KMP; ensure okhttp-jvm in Maven or okhttp in Gradle |
SSLHandshakeException | TLS version mismatch | Check ConnectionSpec; try COMPATIBLE_TLS fallback |
SocketTimeoutException | Server too slow | Increase readTimeout or callTimeout |
ConnectionPool exhaustion | Too many concurrent requests | Increase pool size or use async calls with Dispatcher limits |
IllegalStateException: cache is closed | Cache directory conflict | Ensure single Cache instance per directory |
Certificate pinning failure | Pin mismatch | Update pins after certificate rotation |
IOException: Canceled | Call canceled | Check cancellation logic; don't cancel prematurely |
ProtocolException: HTTP/209 | Invalid HTTP method | OkHttp follows RFC; use POST instead of GET with body |
Maven okhttp artifact empty | KMP artifact issue | Use okhttp-jvm for Maven projects |
| GraalVM native image fails | Missing reflection config | See okcurl module for example GraalVM config |
okhttp-jvm — OkHttp 5.x is Kotlin Multiplatform; the okhttp artifact is empty in Maven. Use okhttp-jvm for JVM projects.Cache in OkHttpClient.Builder.fastFallback(false) if needed.dispatcher(new Dispatcher(executorService)).Accept-Encoding: gzip automatically. Interceptors see compressed data at network level.agents/openai.yaml (opens in a new tab)examples/basic-usage.md (opens in a new tab)examples/caching-examples.md (opens in a new tab)examples/https-examples.md (opens in a new tab)examples/interceptors-examples.md (opens in a new tab)references/caching.md (opens in a new tab)references/calls.md (opens in a new tab)references/configuration.md (opens in a new tab)references/connections.md (opens in a new tab)references/events.md (opens in a new tab)references/https.md (opens in a new tab)references/interceptors.md (opens in a new tab)references/recipes.md (opens in a new tab)references/security.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Generated from the plugin's indexed repository (full-stack-skills/java-skills) — no native marketplace selected
npx claudepluginhub p/full-statck-skills-java-skills39 skills in this plugin
/caffeine-patternsCaffeine JVM 本地缓存技能。覆盖本地缓存 vs 远程缓存(Redis)选择决策树、expireAfterWrite vs expireAfterAccess vs refreshAfterWrite 三种过期策略对比与组合规则(refresh < expire)、CacheLoader加载与reload异步刷新模式、Spring Cache @Cacheable集成、maximumSize驱逐策略、recordStats缓存统计。 纠正 LLM:用 ConcurrentHashMap+手动过期、所有缓存走Redis、refreshAfterWrite > expireAfterWrite导致永远不刷新、CacheLoader返回null导致缓存穿透。/commons-patternsApache Commons 最佳实践模式。从官方文档提炼,覆盖 Commons Lang3(StringUtils千面判空/isEmpty vs isBlank/Validate抛NullPointerException迁移)、Commons IO(IOUtils.toString大文件陷阱/FileUtils.lineIterator逐行读模式/FilenameUtils.normalize路径规范化)、Commons Collections4(CollectionUtils.union/intersection/subtract集合运算)。 纠正 LLM 误用:混淆 StringUtils.isBlank vs isEmpty、IOUtils.toString 读大文件OOM、不知道 LineIterator 逐行读模式、用 lang 而非 lang3 包名。/