### start(inetAddress: InetAddress, port: Int) Source: https://square.github.io/okhttp/5.x/mockwebserver3/mockwebserver3/-mock-web-server/start.html Starts the server on the given address and port. ```kotlin fun start(inetAddress: InetAddress, port: Int) ``` -------------------------------- ### start(port: Int = 0) Source: https://square.github.io/okhttp/5.x/mockwebserver3/mockwebserver3/-mock-web-server/start.html Starts the server on the loopback interface for the given port. ```kotlin @JvmOverloads fun start(port: Int = 0) ``` -------------------------------- ### Gradle Local Properties Example Source: https://square.github.io/okhttp/contribute/contributing Example of a local.properties file for Gradle setup, including the SDK directory and enabling Gradle caching. ```properties sdk.dir=PATH_TO_ANDROID_HOME/sdk org.gradle.caching=true ``` -------------------------------- ### started Source: https://square.github.io/okhttp/5.x/mockwebserver3/mockwebserver3/-mock-web-server/index.html Whether the mock web server has started. ```kotlin val started: Boolean ``` -------------------------------- ### start Source: https://square.github.io/okhttp/5.x/mockwebserver3/mockwebserver3/-mock-web-server/index.html Starts the server on the loopback interface for the given port. ```kotlin @JvmOverloads fun start(port: Int = 0) ``` ```kotlin fun start(inetAddress: InetAddress, port: Int) ``` -------------------------------- ### Task Runner Logging Example Source: https://square.github.io/okhttp/debug_logging Example log output for task enqueues, starts, and finishes in the OkHttp Task Runner. ```log [2020-01-01 00:00:00] Q10000 scheduled after 0 µs: OkHttp ConnectionPool [2020-01-01 00:00:00] Q10000 starting : OkHttp ConnectionPool [2020-01-01 00:00:00] Q10000 run again after 300 s : OkHttp ConnectionPool [2020-01-01 00:00:00] Q10000 finished run in 1 ms: OkHttp ConnectionPool [2020-01-01 00:00:00] Q10001 scheduled after 0 µs: OkHttp squareup.com applyAndAckSettings [2020-01-01 00:00:00] Q10001 starting : OkHttp squareup.com applyAndAckSettings [2020-01-01 00:00:00] Q10003 scheduled after 0 µs: OkHttp squareup.com onSettings [2020-01-01 00:00:00] Q10003 starting : OkHttp squareup.com onSettings [2020-01-01 00:00:00] Q10001 finished run in 3 ms: OkHttp squareup.com applyAndAckSettings [2020-01-01 00:00:00] Q10003 finished run in 528 µs: OkHttp squareup.com onSettings [2020-01-01 00:00:00] Q10000 scheduled after 0 µs: OkHttp ConnectionPool [2020-01-01 00:00:00] Q10000 starting : OkHttp ConnectionPool [2020-01-01 00:00:00] Q10000 run again after 300 s : OkHttp ConnectionPool [2020-01-01 00:00:00] Q10000 finished run in 739 µs: OkHttp ConnectionPool ``` -------------------------------- ### Kotlin Example Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-call/clone.html Example of cloning a call and copying tags. ```kotlin val copy = original.clone() val myTag = original.tag(MyTag::class) if (myTag != null) { copy.tag(MyTag::class) { myTag } } ``` -------------------------------- ### OkHttp Kotlin API Example Source: https://square.github.io/okhttp/changelog Example of using the OkHttp Kotlin API without a builder. ```kotlin val request = Request( url = "https://cash.app/".toHttpUrl(), ) ``` -------------------------------- ### Throttle Body Example Source: https://square.github.io/okhttp/5.x/mockwebserver/okhttp3.mockwebserver/-mock-response/throttle-body.html This example demonstrates how to use `throttleBody` to stream a response body with a delay. ```kotlin val response = MockResponse() .throttleBody(1024, 5, TimeUnit.SECONDS) .setBody("This is a large response body that will be streamed slowly.") server.enqueue(response) ``` -------------------------------- ### Basic Usage Source: https://square.github.io/okhttp/features/caching Example of how to configure OkHttp with a cache. ```kotlin private val client: OkHttpClient = OkHttpClient.Builder() .cache(Cache( directory = File(application.cacheDir, "http_cache"), // $0.05 worth of phone storage in 2020 maxSize = 50L * 1024L * 1024L // 50 MiB )) .build() ``` -------------------------------- ### Posting a File Source: https://square.github.io/okhttp/recipes This example shows how to use a file as a request body. ```kotlin private val client = OkHttpClient() fun run() { val file = File("README.md") val request = Request.Builder() .url("https://api.github.com/markdown/raw") .post(file.asRequestBody(MEDIA_TYPE_MARKDOWN)) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") println(response.body!!.string()) } } companion object { val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType() } ``` ```java public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { File file = new File("README.md"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } ``` -------------------------------- ### Okio Dependency Source: https://square.github.io/okhttp/changelog Example of adding Okio dependency. ```java implementation("com.squareup.okio:okio:2.9.0") ``` -------------------------------- ### Kotlin Example Source: https://square.github.io/okhttp/recipes Demonstrates how to configure and use OkHttp's response caching in Kotlin. ```kotlin private val client: OkHttpClient = OkHttpClient.Builder() .cache(Cache( directory = cacheDirectory, maxSize = 10L * 1024L * 1024L // 10 MiB )) .build() fun run() { val request = Request.Builder() .url("http://publicobject.com/helloworld.txt") .build() val response1Body = client.newCall(request).execute().use { if (!it.isSuccessful) throw IOException("Unexpected code $it") println("Response 1 response: $it") println("Response 1 cache response: ${it.cacheResponse}") println("Response 1 network response: ${it.networkResponse}") return@use it.body!!.string() } val response2Body = client.newCall(request).execute().use { if (!it.isSuccessful) throw IOException("Unexpected code $it") println("Response 2 response: $it") println("Response 2 cache response: ${it.cacheResponse}") println("Response 2 network response: ${it.networkResponse}") return@use it.body!!.string() } println("Response 2 equals Response 1? " + (response1Body == response2Body)) ``` -------------------------------- ### GraalVM Support with Okcurl Source: https://square.github.io/okhttp/changelog Example of building and running Okcurl with GraalVM. ```bash $ ./gradlew okcurl:nativeImage $ ./okcurl/build/graal/okcurl https://cash.app/robots.txt ``` -------------------------------- ### pathSegments examples Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/path-segments.html Examples of pathSegments for different URLs. ```kotlin val pathSegments: List ``` -------------------------------- ### topPrivateDomain Examples Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/top-private-domain.html Examples of how topPrivateDomain() works with different URL formats. ```kotlin http://google.com ``` ```kotlin http://adwords.google.co.uk ``` ```kotlin http://square ``` ```kotlin http://co.uk ``` ```kotlin http://localhost ``` ```kotlin http://127.0.0.1 ``` -------------------------------- ### queryParameter examples Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/query-parameter.html Examples of how queryParameter works with different URL formats. ```kotlin fun queryParameter(name: String): String? ``` -------------------------------- ### OkHttp BOM Example (Gradle) Source: https://square.github.io/okhttp/changelogs/changelog_4x Example of how to use the OkHttp Bill of Materials (BOM) in Gradle to manage OkHttp artifact versions. ```gradle dependencies { api(platform("com.squareup.okhttp3:okhttp-bom:4.4.0")) api("com.squareup.okhttp3:okhttp") // No version! api("com.squareup.okhttp3:logging-interceptor") // No version! } ``` -------------------------------- ### Java Example Source: https://square.github.io/okhttp/recipes Demonstrates how to configure and use OkHttp's response caching in Java. ```java private final OkHttpClient client; public CacheResponse(File cacheDirectory) throws Exception { int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(cacheDirectory, cacheSize); client = new OkHttpClient.Builder() .cache(cache) .build(); } public void run() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); String response1Body; try (Response response1 = client.newCall(request).execute()) { if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); response1Body = response1.body().string(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); } String response2Body; try (Response response2 = client.newCall(request).execute()) { if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); } System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); } ``` -------------------------------- ### Java Example Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-call/clone.html Example of cloning a call and copying tags in Java. ```java Call copy = original.clone(); MyTag myTag = original.tag(MyTag.class); if (myTag != null) { copy.tag(MyTag.class, () -> myTag); } ``` -------------------------------- ### Okio Version Upgrade Example Source: https://square.github.io/okhttp/changelogs/changelog_4x Example of how to upgrade the Okio dependency to version 2.4.3. ```gradle implementation("com.squareup.okio:okio:2.4.3") ``` -------------------------------- ### Pruning the Cache - Evict All Source: https://square.github.io/okhttp/features/caching Example of how to evict all items from the cache. ```kotlin cache.evictAll() ``` -------------------------------- ### get Function Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-request/-builder/index.html Sets the request method to GET. ```kotlin open fun get(): Request.Builder ``` -------------------------------- ### get(name: String) Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/-builder/index.html Gets the header value for the specified name. Equivalent to `build().get(name)`, but potentially faster. ```kotlin operator fun get(name: String): String? ``` -------------------------------- ### GraalVM Support with OkCurl Source: https://square.github.io/okhttp/changelogs/changelog Example of building and running OkCurl with GraalVM native image support. ```bash ./gradlew okcurl:nativeImage ./okcurl/build/graal/okcurl https://cash.app/robots.txt ``` -------------------------------- ### Enable Zstandard compression Source: https://square.github.io/okhttp/changelog Example of how to enable Zstandard (zstd) compression for OkHttp client by adding a CompressionInterceptor. ```kotlin val client = OkHttpClient.Builder() .addInterceptor(CompressionInterceptor(Zstd, Gzip)) .build() ``` -------------------------------- ### get Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-handshake/-companion/index.html Companion function to create a Handshake instance. ```kotlin fun get( tlsVersion: TlsVersion, cipherSuite: CipherSuite, peerCertificates: List<>, localCertificates: List<>): Handshake ``` -------------------------------- ### Customize a shared OkHttpClient instance with newBuilder() Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-ok-http-client/index.html This example shows the single instance with default configurations. ```java public final OkHttpClient client = new OkHttpClient.Builder() .readTimeout(1000, TimeUnit.MILLISECONDS) .writeTimeout(1000, TimeUnit.MILLISECONDS) .build(); ``` -------------------------------- ### Get Protocol by String Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-protocol/-companion/index.html Returns the protocol identified by the given string. ```kotlin fun get(protocol: String): Protocol ``` -------------------------------- ### HTTP/2 Frame Logging Example Source: https://square.github.io/okhttp/debug_logging Example log output for inbound (<<) and outbound (>>) frames for HTTP/2 connections. ```log [2020-01-01 00:00:00] >> CONNECTION 505249202a20485454502f322e300d0a0d0a534d0d0a0d0a [2020-01-01 00:00:00] >> 0x00000000 6 SETTINGS [2020-01-01 00:00:00] >> 0x00000000 4 WINDOW_UPDATE [2020-01-01 00:00:00] >> 0x00000003 47 HEADERS END_STREAM|END_HEADERS [2020-01-01 00:00:00] << 0x00000000 6 SETTINGS [2020-01-01 00:00:00] << 0x00000000 0 SETTINGS ACK [2020-01-01 00:00:00] << 0x00000000 4 WINDOW_UPDATE [2020-01-01 00:00:00] >> 0x00000000 0 SETTINGS ACK [2020-01-01 00:00:00] << 0x00000003 322 HEADERS END_HEADERS [2020-01-01 00:00:00] << 0x00000003 288 DATA [2020-01-01 00:00:00] << 0x00000003 0 DATA END_STREAM [2020-01-01 00:00:00] << 0x00000000 8 GOAWAY [2020-01-01 00:00:05] << 0x00000000 8 GOAWAY ``` -------------------------------- ### Post Streaming Source: https://square.github.io/okhttp/recipes This example demonstrates how to POST a request body as a stream, generating content as it's written and streaming directly into an Okio buffered sink. ```kotlin private val client = OkHttpClient() fun run() { val requestBody = object : RequestBody() { override fun contentType() = MEDIA_TYPE_MARKDOWN override fun writeTo(sink: BufferedSink) { sink.writeUtf8("Numbers\n") sink.writeUtf8("-------\n") for (i in 2..997) { sink.writeUtf8(String.format(" * $i = ${factor(i)}\n")) } } private fun factor(n: Int): String { for (i in 2 until n) { val x = n / i if (x * i == n) return "${factor(x)} × $i" } return n.toString() } } val request = Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") println(response.body!!.string()) } } companion object { val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType() } ``` ```java public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_MARKDOWN; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("Numbers\n"); sink.writeUtf8("-------\n"); for (int i = 2; i <= 997; i++) { sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i))); } } private String factor(int n) { for (int i = 2; i < n; i++) { int x = n / i; if (x * i == n) return factor(x) + " × " + i; } return Integer.toString(n); } }; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } ``` -------------------------------- ### Posting a String Source: https://square.github.io/okhttp/recipes Example of how to send a string as a request body using HTTP POST. ```kotlin private val client = OkHttpClient() fun run() { val postBody = """ |Releases |-------- | | * _1.0_ May 6, 2013 | * _1.1_ June 15, 2013 | * _1.2_ August 11, 2013 |""".trimMargin() val request = Request.Builder() .url("https://api.github.com/markdown/raw") .post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN)) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") println(response.body!!.string()) } } companion object { val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType() } ``` ```java public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { String postBody = "" + "Releases\n" + "--------\n" + "\n" + " * _1.0_ May 6, 2013\n" + " * _1.1_ June 15, 2013\n" + " * _1.2_ August 11, 2013\n"; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } ``` -------------------------------- ### Java Example Source: https://square.github.io/okhttp/recipes This Java code snippet demonstrates how to achieve the same JSON parsing with OkHttp and Moshi using Java. ```Java private final OkHttpClient client = new OkHttpClient(); private final Moshi moshi = new Moshi.Builder().build(); private final JsonAdapter gistJsonAdapter = moshi.adapter(Gist.class); public void run() throws Exception { Request request = new Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gistJsonAdapter.fromJson(response.body().source()); for (Map.Entry entry : gist.files.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue().content); } } } static class Gist { Map files; } static class GistFile { String content; } ``` -------------------------------- ### Upload Progress Example Source: https://square.github.io/okhttp/recipes This Java code demonstrates how to create a RequestBody that tracks upload progress using a ProgressListener. ```java public static void main(String... args) throws Exception { new UploadProgress().run(); } private static class ProgressRequestBody extends RequestBody { private final ProgressListener progressListener; private final RequestBody delegate; public ProgressRequestBody(RequestBody delegate, ProgressListener progressListener) { this.delegate = delegate; this.progressListener = progressListener; } @Override public MediaType contentType() { return delegate.contentType(); } @Override public long contentLength() throws IOException { return delegate.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink bufferedSink = Okio.buffer(sink(sink)); delegate.writeTo(bufferedSink); bufferedSink.flush(); } public Sink sink(Sink sink) { return new ForwardingSink(sink) { private long totalBytesWritten = 0L; private boolean completed = false; @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); totalBytesWritten += byteCount; progressListener.update(totalBytesWritten, contentLength(), completed); } @Override public void close() throws IOException { super.close(); if (!completed) { completed = true; progressListener.update(totalBytesWritten, contentLength(), completed); } } }; } } interface ProgressListener { void update(long bytesWritten, long contentLength, boolean done); } ``` -------------------------------- ### Preemptive Authentication Example Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-authenticator/index.html This code snippet demonstrates how to handle preemptive authentication by checking for the 'OkHttp-Preemptive' challenge and adding a 'Proxy-Authorization' header. ```java for (Challenge challenge : response.challenges()) { // If this is preemptive auth, use a preemptive credential. if (challenge.scheme().equalsIgnoreCase("OkHttp-Preemptive")) { return response.request().newBuilder() .header("Proxy-Authorization", "secret") .build(); } } return null; // Didn't find a preemptive auth scheme. ``` -------------------------------- ### Cipher Suites by String Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-connection-spec/-builder/cipher-suites.html This example shows how to set the cipher suites using their string names. ```kotlin fun cipherSuites(vararg cipherSuites: String): ConnectionSpec.Builder ``` -------------------------------- ### Composing and printing a URL for Google search Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/index.html This example demonstrates how to compose a URL with scheme, host, path segment, and query parameters, and then print it. ```java HttpUrl url = new HttpUrl.Builder() .scheme("https") .host("www.google.com") .addPathSegment("search") .addQueryParameter("q", "polar bears") .build(); System.out.println(url); ``` -------------------------------- ### Synchronous Get Source: https://square.github.io/okhttp/recipes Download a file, print its headers, and print its response body as a string. ```Kotlin private val client = OkHttpClient() fun run() { val request = Request.Builder() .url("https://publicobject.com/helloworld.txt") .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") for ((name, value) in response.headers) { println("$name: $value") } println(response.body!!.string()) } } ``` ```Java private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("https://publicobject.com/helloworld.txt") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string()); } } ``` -------------------------------- ### Resolving a relative URL Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/index.html This example demonstrates how to resolve a relative URL against a base URL to get the final, absolute URL. ```java HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos"); HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc"); System.out.println(link); ``` -------------------------------- ### Kotlin Example Source: https://square.github.io/okhttp/recipes This Kotlin code snippet shows how to use OkHttp to fetch JSON data from a GitHub API and parse it into Kotlin data classes using Moshi. ```Kotlin private val client = OkHttpClient() private val moshi = Moshi.Builder().build() private val gistJsonAdapter = moshi.adapter(Gist::class.java) fun run() { val request = Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") val gist = gistJsonAdapter.fromJson(response.body!!.source()) for ((key, value) in gist!!.files!!) { println(key) println(value.content) } } } @JsonClass(generateAdapter = true) data class Gist(var files: Map?) @JsonClass(generateAdapter = true) data class GistFile(var content: String?) ``` -------------------------------- ### Create a shared instance with the default settings Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-ok-http-client/index.html Use `new OkHttpClient()` to create a shared instance with the default settings. ```java public final OkHttpClient client = new OkHttpClient(); ``` -------------------------------- ### key Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-cache/-companion/index.html key ```kotlin fun key(url: HttpUrl): String ``` -------------------------------- ### Initialize OkHttp with ApplicationContext Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-ok-http/initialize.html This function configures the ApplicationContext for OkHttp. It's primarily needed when the AndroidX Startup Initializer is disabled or when running Robolectric tests. The absence of a valid Context can affect cookie and URL domain handling. ```kotlin fun initialize(applicationContext: Context) ``` -------------------------------- ### Setting up Certificate Pinning Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-certificate-pinner/index.html This code snippet demonstrates how to set up certificate pinning for a specific hostname. It includes adding a placeholder pin, building the CertificatePinner and OkHttpClient, and executing a request which is expected to fail. ```java String hostname = "publicobject.com"; CertificatePinner certificatePinner = new CertificatePinner.Builder() .add(hostname, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") .build(); OkHttpClient client = OkHttpClient.Builder() .certificatePinner(certificatePinner) .build(); Request request = new Request.Builder() .url("https://" + hostname) .build(); client.newCall(request).execute(); ``` -------------------------------- ### initialize() function signature Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-cache/initialize.html The function signature for initializing the cache. ```kotlin fun initialize() ``` -------------------------------- ### Java Modules Error Example Source: https://square.github.io/okhttp Example of a Java Modules error when accessing internal OkHttp packages. ```java error: package okhttp3.internal.platform is not visible okhttp3.internal.platform.Platform.get(); ^ (package okhttp3.internal.platform is declared in module okhttp3, which does not export it to module com.bigco.sdk) ``` -------------------------------- ### Asynchronous Get Source: https://square.github.io/okhttp/recipes Download a file on a worker thread, and get called back when the response is readable. ```Kotlin private val client = OkHttpClient() fun run() { val request = Request.Builder() .url("http://publicobject.com/helloworld.txt") .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() } override fun onResponse(call: Call, response: Response) { response.use { if (!response.isSuccessful) throw IOException("Unexpected code $response") for ((name, value) in response.headers) { println("$name: $value") } println(response.body!!.string()) } } }) } ``` ```Java private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); 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 responseBody = response.body()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(responseBody.string()); } } }); } ``` -------------------------------- ### Empty headers Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/-companion/index.html Empty headers. ```kotlin val EMPTY: Headers ``` -------------------------------- ### SocketPolicy Functions Source: https://square.github.io/okhttp/5.x/mockwebserver/okhttp3.mockwebserver/-socket-policy/index.html This lists the functions available for the SocketPolicy enum, specifically 'valueOf' to get an enum constant by name and 'values' to get an array of all constants. ```kotlin fun valueOf(value: String): SocketPolicy fun values(): Array ``` -------------------------------- ### Example Certificate Chain Source: https://square.github.io/okhttp/5.x/okhttp-tls/okhttp3.tls/-held-certificate/index.html An example of a certificate chain used to establish a secure connection to https://www.squareup.com/, including details of the common name, subject alternative names, validity, public key, and signature for each certificate in the chain. ```text www.squareup.com certificate: Common Name: www.squareup.com Subject Alternative Names: www.squareup.com, squareup.com, account.squareup.com... Validity: 2018-07-03T20:18:17Z – 2019-08-01T20:48:15Z Public Key: d107beecc17325f55da976bcbab207ba4df68bd3f8fce7c3b5850311128264fd53e1baa342f58d93... Signature: 1fb0e66fac05322721fe3a3917f7c98dee1729af39c99eab415f22d8347b508acdf0bab91781c3720... signed by intermediate certificate: Common Name: Entrust Certification Authority - L1M Subject Alternative Names: none Validity: 2014-12-15T15:25:03Z – 2030-10-15T15:55:03Z Public Key: d081c13923c2b1d1ecf757dd55243691202248f7fcca520ab0ab3f33b5b08407f6df4e7ab0fb9822... Signature: b487c784221a29c0a478ecf54f1bb484976f77eed4cf59afa843962f1d58dea6f3155b2ed9439c4c4... signed by root certificate: Common Name: Entrust Root Certification Authority - G2 Subject Alternative Names: none Validity: 2009-07-07T17:25:54Z – 2030-12-07T17:55:54Z Public Key: ba84b672db9e0c6be299e93001a776ea32b895411ac9da614e5872cffef68279bf7361060aa527d8... Self-signed Signature: 799f1d96c6b6793f228d87d3870304606a6b9a2e59897311ac43d1f513ff8d392bc0f... ``` -------------------------------- ### redact() function Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/redact.html Example of how the redact function works. ```kotlin fun redact(): String ``` -------------------------------- ### protocol Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-response/-builder/index.html Sets the protocol. ```kotlin open fun protocol(protocol: Protocol): Response.Builder ``` -------------------------------- ### Original Headers Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/equals.html Example of original headers. ```http Content-Type: text/html Content-Length: 50 ``` -------------------------------- ### add(line: String) Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/-builder/add.html Add an header line containing a field name, a literal colon, and a value. ```kotlin fun add(line: String): Headers.Builder ``` -------------------------------- ### Delete Cache Source: https://square.github.io/okhttp/features/caching Example of how to delete the entire cache. ```kotlin cache.delete() ``` -------------------------------- ### Different Values Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/equals.html Example of headers with different values. ```http Content-Type: text/html Content-Length: 050 ``` -------------------------------- ### Running Android Tests Source: https://square.github.io/okhttp/contribute/contributing Command to run Android tests using Gradle, specifying the Android SDK root and enabling Android build. ```bash $ ANDROID_SDK_ROOT=PATH_TO_ANDROID_HOME/sdk ./gradlew :android-test:connectedCheck -PandroidBuild=true ``` -------------------------------- ### Different Case Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/equals.html Example of headers with different case. ```http content-type: text/html content-length: 50 ``` -------------------------------- ### Different Order Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/equals.html Example of headers with different order. ```http Content-Length: 50 Content-Type: text/html ``` -------------------------------- ### Create a shared instance with custom settings Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-ok-http-client/index.html Or use `new OkHttpClient.Builder()` to create a shared instance with custom settings. ```java public final OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new HttpLoggingInterceptor()) .cache(new Cache(cacheDir, cacheSize)) .build(); ``` -------------------------------- ### getTail Function Source: https://square.github.io/okhttp/5.x/okcurl/okhttp3.curl.logging/-one-line-log-format/index.html Gets the tail string for a Handler. ```java open fun getTail(p0: Handler): String ``` -------------------------------- ### getHead Function Source: https://square.github.io/okhttp/5.x/okcurl/okhttp3.curl.logging/-one-line-log-format/index.html Gets the head string for a Handler. ```java open fun getHead(p0: Handler): String ``` -------------------------------- ### build() Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/-builder/index.html Builds the Headers object. ```kotlin fun build(): Headers ``` -------------------------------- ### Set MIME Type Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-multipart-body/-builder/set-type.html Example of setting the MIME type for a MultipartBody.Builder. ```kotlin fun setType(type: MediaType): MultipartBody.Builder ``` -------------------------------- ### Get a URL Source: https://square.github.io/okhttp This program downloads a URL and prints its contents as a string. ```java OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } ``` -------------------------------- ### toHttpUrl Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-http-url/-companion/index.html Returns a new HttpUrl representing this. ```kotlin fun String.toHttpUrl(): HttpUrl ``` -------------------------------- ### GraalVM Native Image Build Source: https://square.github.io/okhttp Commands to build a native image with GraalVM. ```bash $ ./gradlew okcurl:nativeImage $ ./okcurl/build/graal/okcurl https://httpbin.org/get ``` -------------------------------- ### Application Interceptor Example Source: https://square.github.io/okhttp/features/interceptors Registering an application interceptor by calling addInterceptor() on OkHttpClient.Builder. ```Java OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor()) .build(); Request request = new Request.Builder() .url("http://www.publicobject.com/helloworld.txt") .header("User-Agent", "OkHttp Example") .build(); Response response = client.newCall(request).execute(); response.body().close(); ``` -------------------------------- ### add(name: String, value: String) Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-headers/-builder/add.html Add a header with the specified name and value. Does validation of header names and values. ```kotlin fun add(name: String, value: String): Headers.Builder ``` -------------------------------- ### Part constructor Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-multipart-reader/-part/index.html Constructs a new Part with the given headers and body. ```kotlin constructor(headers: Headers, body: BufferedSource) ``` -------------------------------- ### asRequestBody from Path Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-request-body/-companion/index.html Returns a new request body that transmits the content of this Path. ```kotlin fun Path.asRequestBody(fileSystem: FileSystem, contentType: MediaType? = null): RequestBody ``` -------------------------------- ### Network Interceptor Example Source: https://square.github.io/okhttp/features/interceptors Registering a network interceptor by calling addNetworkInterceptor() instead of addInterceptor(). ```Java OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(new LoggingInterceptor()) .build(); Request request = new Request.Builder() .url("http://www.publicobject.com/helloworld.txt") .header("User-Agent", "OkHttp Example") .build(); Response response = client.newCall(request).execute(); response.body().close(); ``` -------------------------------- ### Interceptor Implementation Example Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-interceptor/index.html A good way to signal a failure is with a synthetic HTTP response. ```kotlin @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { if (myConfig.isInvalid()) { return Response.Builder() .request(chain.request()) .protocol(Protocol.HTTP_1_1) .code(400) .message("client config invalid") .body("client config invalid".toResponseBody(null)) .build() } return chain.proceed(chain.request()) } ``` -------------------------------- ### BASIC Log Example Source: https://square.github.io/okhttp/5.x/logging-interceptor/okhttp3.logging/-http-logging-interceptor/-level/-b-a-s-i-c/index.html Logs request and response lines. ```text --> POST /greeting http/1.1 (3-byte body) <-- 200 OK (22ms, 6-byte body) ``` -------------------------------- ### client Source: https://square.github.io/okhttp/5.x/okhttp-dnsoverhttps/okhttp3.dnsoverhttps/-dns-over-https/-builder/index.html Sets the OkHttpClient to use. ```java fun client(client: OkHttpClient): ``` -------------------------------- ### Posting form parameters Source: https://square.github.io/okhttp/recipes Demonstrates how to use `FormBody.Builder` to build a request body for form parameters, similar to an HTML form. ```kotlin private val client = OkHttpClient() fun run() { val formBody = FormBody.Builder() .add("search", "Jurassic Park") .build() val request = Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") println(response.body!!.string()) } } ``` ```java private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormBody.Builder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } ``` -------------------------------- ### HEADERS Example Source: https://square.github.io/okhttp/5.x/logging-interceptor/okhttp3.logging/-http-logging-interceptor/-level/-h-e-a-d-e-r-s/index.html Logs request and response lines and their respective headers. ```http --> POST /greeting http/1.1 Host: example.com Content-Type: plain/text Content-Length: 3 --> END POST <-- 200 OK (22ms) Content-Type: plain/text Content-Length: 6 <-- END HTTP ``` -------------------------------- ### peek Function Source: https://square.github.io/okhttp/5.x/mockwebserver/okhttp3.mockwebserver/-dispatcher/index.html Opens a new connection to the server and returns the MockResponse. ```kotlin open fun peek(): MockResponse ``` -------------------------------- ### request Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-response/-builder/index.html Sets the request. ```kotlin open fun request(request: Request): Response.Builder ``` -------------------------------- ### Cipher Suites by CipherSuite enum Source: https://square.github.io/okhttp/5.x/okhttp/okhttp3/-connection-spec/-builder/cipher-suites.html This example shows how to set the cipher suites using the CipherSuite enum. ```kotlin fun cipherSuites(vararg cipherSuites: CipherSuite): ConnectionSpec.Builder ``` -------------------------------- ### useHttps Source: https://square.github.io/okhttp/5.x/mockwebserver3/mockwebserver3/-mock-web-server/index.html Serve requests with HTTPS rather than otherwise. ```kotlin fun useHttps(sslSocketFactory: SSLSocketFactory) ```