Skip to content

Commit 7c80296

Browse files
committed
Add Kotlin listings for OkHttp recipes doc
1 parent 253d2ea commit 7c80296

25 files changed

+1606
-81
lines changed

build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ buildscript {
3737
'junit': "junit:junit:${versions.junit}",
3838
'kotlinStdlib': "org.jetbrains.kotlin:kotlin-stdlib:${versions.kotlin}",
3939
'moshi': "com.squareup.moshi:moshi:${versions.moshi}",
40+
'moshiKotlin': "com.squareup.moshi:moshi-kotlin-codegen:${versions.moshi}",
4041
'okio': "com.squareup.okio:okio:${versions.okio}",
4142
'openjsse': "org.openjsse:openjsse:${versions.openjsse}"
4243
]

docs/connections.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Connections
33

44
Although you provide only the URL, OkHttp plans its connection to your webserver using three types: URL, Address, and Route.
55

6-
#### [URLs](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-http-url/)
6+
### [URLs](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-http-url/)
77

88
URLs (like `https://github.com/square/okhttp`) are fundamental to HTTP and the Internet. In addition to being a universal, decentralized naming scheme for everything on the web, they also specify how to access web resources.
99

@@ -14,21 +14,21 @@ URLs are abstract:
1414

1515
They're also concrete: each URL identifies a specific path (like `/square/okhttp`) and query (like `?q=sharks&lang=en`). Each webserver hosts many URLs.
1616

17-
#### [Addresses](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-address/)
17+
### [Addresses](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-address/)
1818

1919
Addresses specify a webserver (like `github.com`) and all of the **static** configuration necessary to connect to that server: the port number, HTTPS settings, and preferred network protocols (like HTTP/2 or SPDY).
2020

2121
URLs that share the same address may also share the same underlying TCP socket connection. Sharing a connection has substantial performance benefits: lower latency, higher throughput (due to [TCP slow start](http://www.igvita.com/2011/10/20/faster-web-vs-tcp-slow-start/)) and conserved battery. OkHttp uses a [ConnectionPool](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-connection-pool/) that automatically reuses HTTP/1.x connections and multiplexes HTTP/2 and SPDY connections.
2222

2323
In OkHttp some fields of the address come from the URL (scheme, hostname, port) and the rest come from the [OkHttpClient](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/).
2424

25-
#### [Routes](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-route/)
25+
### [Routes](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-route/)
2626

2727
Routes supply the **dynamic** information necessary to actually connect to a webserver. This is the specific IP address to attempt (as discovered by a DNS query), the exact proxy server to use (if a [ProxySelector](http://developer.android.com/reference/java/net/ProxySelector.html) is in use), and which version of TLS to negotiate (for HTTPS connections).
2828

2929
There may be many routes for a single address. For example, a webserver that is hosted in multiple datacenters may yield multiple IP addresses in its DNS response.
3030

31-
#### [Connections](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-connection/)
31+
### [Connections](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-connection/)
3232

3333
When you request a URL with OkHttp, here's what it does:
3434

docs/https.md

Lines changed: 98 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -43,46 +43,123 @@ OkHttpClient client = new OkHttpClient.Builder()
4343
.build();
4444
```
4545

46-
#### [Certificate Pinning](https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.java)
46+
### Certificate Pinning ([.kt][CertificatePinningKotlin], [.java][CertificatePinningJava])
4747

4848
By default, OkHttp trusts the certificate authorities of the host platform. This strategy maximizes connectivity, but it is subject to certificate authority attacks such as the [2011 DigiNotar attack](http://www.computerworld.com/article/2510951/cybercrime-hacking/hackers-spied-on-300-000-iranians-using-fake-google-certificate.html). It also assumes your HTTPS servers’ certificates are signed by a certificate authority.
4949

5050
Use [CertificatePinner](http://square.github.io/okhttp/4.x/okhttp/okhttp3/-certificate-pinner/) to restrict which certificates and certificate authorities are trusted. Certificate pinning increases security, but limits your server team’s abilities to update their TLS certificates. **Do not use certificate pinning without the blessing of your server’s TLS administrator!**
5151

52-
```java
53-
public CertificatePinning() {
54-
client = new OkHttpClient.Builder()
55-
.certificatePinner(new CertificatePinner.Builder()
56-
.add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
57-
.build())
58-
.build();
52+
```Kotlin tab=
53+
private val client = OkHttpClient.Builder()
54+
.certificatePinner(
55+
CertificatePinner.Builder()
56+
.add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
57+
.build())
58+
.build()
59+
60+
fun run() {
61+
val request = Request.Builder()
62+
.url("https://publicobject.com/robots.txt")
63+
.build()
64+
65+
client.newCall(request).execute().use { response ->
66+
if (!response.isSuccessful) throw IOException("Unexpected code $response")
67+
68+
for (certificate in response.handshake!!.peerCertificates) {
69+
println(CertificatePinner.pin(certificate))
70+
}
71+
}
5972
}
73+
```
74+
75+
```Java tab=
76+
private final OkHttpClient client = new OkHttpClient.Builder()
77+
.certificatePinner(
78+
new CertificatePinner.Builder()
79+
.add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
80+
.build())
81+
.build();
6082

6183
public void run() throws Exception {
6284
Request request = new Request.Builder()
6385
.url("https://publicobject.com/robots.txt")
6486
.build();
6587

66-
Response response = client.newCall(request).execute();
67-
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
88+
try (Response response = client.newCall(request).execute()) {
89+
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
6890

69-
for (Certificate certificate : response.handshake().peerCertificates()) {
70-
System.out.println(CertificatePinner.pin(certificate));
91+
for (Certificate certificate : response.handshake().peerCertificates()) {
92+
System.out.println(CertificatePinner.pin(certificate));
93+
}
7194
}
7295
}
7396
```
7497

75-
#### [Customizing Trusted Certificates](https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java)
98+
### Customizing Trusted Certificates ([.kt][CustomTrustKotlin], [.java][CustomTrustJava])
7699

77100
The full code sample shows how to replace the host platform’s certificate authorities with your own set. As above, **do not use custom certificates without the blessing of your server’s TLS administrator!**
78101

79-
```java
102+
```Kotlin tab=
103+
private val client: OkHttpClient
104+
105+
init {
106+
val trustManager = trustManagerForCertificates(trustedCertificatesInputStream())
107+
val sslContext = SSLContext.getInstance("TLS")
108+
sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
109+
val sslSocketFactory = sslContext.socketFactory
110+
111+
client = OkHttpClient.Builder()
112+
.sslSocketFactory(sslSocketFactory, trustManager)
113+
.build()
114+
}
115+
116+
fun run() {
117+
val request = Request.Builder()
118+
.url("https://publicobject.com/helloworld.txt")
119+
.build()
120+
121+
client.newCall(request).execute().use { response ->
122+
if (!response.isSuccessful) throw IOException("Unexpected code $response")
123+
124+
for ((name, value) in response.headers) {
125+
println("$name: $value")
126+
}
127+
128+
println(response.body!!.string())
129+
}
130+
}
131+
132+
/**
133+
* Returns an input stream containing one or more certificate PEM files. This implementation just
134+
* embeds the PEM files in Java strings; most applications will instead read this from a resource
135+
* file that gets bundled with the application.
136+
*/
137+
private fun trustedCertificatesInputStream(): InputStream {
138+
... // Full source omitted. See sample.
139+
}
140+
141+
private fun trustManagerForCertificates(inputStream: InputStream): X509TrustManager {
142+
... // Full source omitted. See sample.
143+
}
144+
```
145+
146+
```Java tab=
80147
private final OkHttpClient client;
81148

82149
public CustomTrust() {
83-
SSLContext sslContext = sslContextForTrustedCertificates(trustedCertificatesInputStream());
150+
X509TrustManager trustManager;
151+
SSLSocketFactory sslSocketFactory;
152+
try {
153+
trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
154+
SSLContext sslContext = SSLContext.getInstance("TLS");
155+
sslContext.init(null, new TrustManager[] { trustManager }, null);
156+
sslSocketFactory = sslContext.getSocketFactory();
157+
} catch (GeneralSecurityException e) {
158+
throw new RuntimeException(e);
159+
}
160+
84161
client = new OkHttpClient.Builder()
85-
.sslSocketFactory(sslContext.getSocketFactory())
162+
.sslSocketFactory(sslSocketFactory, trustManager)
86163
.build();
87164
}
88165

@@ -103,3 +180,8 @@ The full code sample shows how to replace the host platform’s certificate auth
103180
... // Full source omitted. See sample.
104181
}
105182
```
183+
184+
[CustomTrustJava]: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java
185+
[CustomTrustKotlin]: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt
186+
[CertificatePinningJava]: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.java
187+
[CertificatePinningKotlin]: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/kt/CertificatePinning.kt

docs/interceptors.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Interceptors can be chained. Suppose you have both a compressing interceptor and
2929

3030
![Interceptors Diagram](images/[email protected])
3131

32-
#### Application Interceptors
32+
### Application Interceptors
3333

3434
Interceptors are registered as either _application_ or _network_ interceptors. We'll use the `LoggingInterceptor` defined above to show the difference.
3535

@@ -64,7 +64,7 @@ Connection: keep-alive
6464

6565
We can see that we were redirected because `response.request().url()` is different from `request.url()`. The two log statements log two different URLs.
6666

67-
#### Network Interceptors
67+
### Network Interceptors
6868

6969
Registering a network interceptor is quite similar. Call `addNetworkInterceptor()` instead of `addInterceptor()`:
7070

@@ -113,7 +113,7 @@ Connection: keep-alive
113113

114114
The network requests also contain more data, such as the `Accept-Encoding: gzip` header added by OkHttp to advertise support for response compression. The network interceptor's `Chain` has a non-null `Connection` that can be used to interrogate the IP address and TLS configuration that were used to connect to the webserver.
115115

116-
#### Choosing between application and network interceptors
116+
### Choosing between application and network interceptors
117117

118118
Each interceptor chain has relative merits.
119119

@@ -132,7 +132,7 @@ Each interceptor chain has relative merits.
132132
* Observe the data just as it will be transmitted over the network.
133133
* Access to the `Connection` that carries the request.
134134

135-
#### Rewriting Requests
135+
### Rewriting Requests
136136

137137
Interceptors can add, remove, or replace request headers. They can also transform the body of those requests that have one. For example, you can use an application interceptor to add request body compression if you're connecting to a webserver known to support it.
138138

@@ -172,7 +172,7 @@ final class GzipRequestInterceptor implements Interceptor {
172172
}
173173
```
174174

175-
#### Rewriting Responses
175+
### Rewriting Responses
176176

177177
Symmetrically, interceptors can rewrite response headers and transform the response body. This is generally more dangerous than rewriting request headers because it may violate the webserver's expectations!
178178

0 commit comments

Comments
 (0)