aboutsummaryrefslogtreecommitdiffstats
path: root/samples
diff options
context:
space:
mode:
authorNeil Fuller <nfuller@google.com>2015-01-20 09:39:41 +0000
committerNeil Fuller <nfuller@google.com>2015-01-20 12:01:46 +0000
commite78f117bcbd6b57d783737107f445ef75ecb474a (patch)
tree6aeb5ecee431742785d8196f39eace37c7a87e63 /samples
parent686cfbde70b55b77360f3401dedf580eea6d47f9 (diff)
downloadplatform_external_okhttp-e78f117bcbd6b57d783737107f445ef75ecb474a.tar.gz
platform_external_okhttp-e78f117bcbd6b57d783737107f445ef75ecb474a.tar.bz2
platform_external_okhttp-e78f117bcbd6b57d783737107f445ef75ecb474a.zip
Pull latest OkHttp code from upstream
okio: okio is now managed upstream as a separate project but has been included here as a sub directory: the okio version here is intended only for use with OkHttp. okio is synced to upstream commit 82358df7f09e18aa42348836c614212085bbf045. See okio/README.android for local changed needed to make it compile. okhttp: This is effectively an upgrade from a snapshot close to OkHttp 1.5 with Android additions to a snapshot close to OkHttp 2.2. okhttp was synced to upstream commit 0a197466608681593cc9be9487965a0b1d5c244c See README.android for local changes needed to make it compile. Most of the old Android changes have been pushed upstream and other upstream changes have been made to keep OkHttp working on Android. TLS fallback changes have not been upstreamed yet: bcce0a3d26d66d33beb742ae2adddb3b7db5ad08 ede2bf1af0917482da8ccb7b048130592034253d This means that some CTS tests will start to fail. A later commit will fix those changes when it has been accepted upstream. There are associated changes in libcore and frameworks/base. Change-Id: I0a68b27b1ec7067be452671bc591edfd84e310f2
Diffstat (limited to 'samples')
-rw-r--r--samples/crawler/pom.xml2
-rw-r--r--samples/crawler/src/main/java/com/squareup/okhttp/sample/Crawler.java43
-rw-r--r--samples/guide/pom.xml6
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/guide/GetExample.java40
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java60
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/AccessHeaders.java45
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/AsynchronousGet.java54
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/Authenticate.java58
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/CacheResponse.java63
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/CancelCall.java62
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/CertificatePinning.java55
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/CheckHandshake.java64
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/ConfigureTimeouts.java45
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/LoggingInterceptors.java58
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/ParseResponseWithGson.java54
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/PerCallSettings.java56
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/PostFile.java49
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/PostForm.java46
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java62
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/PostStreaming.java69
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/PostString.java54
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/RequestBodyCompression.java100
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/RewriteResponseCacheControl.java77
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/SynchronousGet.java46
-rw-r--r--samples/guide/src/main/java/com/squareup/okhttp/recipes/WebSocketEcho.java70
-rw-r--r--samples/pom.xml2
-rw-r--r--samples/simple-client/pom.xml2
-rw-r--r--samples/simple-client/src/main/java/com/squareup/okhttp/sample/OkHttpContributors.java19
-rw-r--r--samples/static-server/pom.xml2
-rw-r--r--samples/static-server/src/main/java/com/squareup/okhttp/sample/SampleServer.java10
30 files changed, 1260 insertions, 113 deletions
diff --git a/samples/crawler/pom.xml b/samples/crawler/pom.xml
index 0015f7c..2be2bab 100644
--- a/samples/crawler/pom.xml
+++ b/samples/crawler/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.squareup.okhttp.sample</groupId>
<artifactId>sample-parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
+ <version>2.3.0-SNAPSHOT</version>
</parent>
<artifactId>crawler</artifactId>
diff --git a/samples/crawler/src/main/java/com/squareup/okhttp/sample/Crawler.java b/samples/crawler/src/main/java/com/squareup/okhttp/sample/Crawler.java
index d80c13f..24383fe 100644
--- a/samples/crawler/src/main/java/com/squareup/okhttp/sample/Crawler.java
+++ b/samples/crawler/src/main/java/com/squareup/okhttp/sample/Crawler.java
@@ -15,17 +15,14 @@
*/
package com.squareup.okhttp.sample;
-import com.squareup.okhttp.HttpResponseCache;
-import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
-import com.squareup.okhttp.internal.http.OkHeaders;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
-import java.nio.charset.Charset;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -40,11 +37,9 @@ import org.jsoup.nodes.Element;
* Fetches HTML from a requested URL, follows the links, and repeats.
*/
public final class Crawler {
- public static final Charset UTF_8 = Charset.forName("UTF-8");
-
private final OkHttpClient client;
private final Set<URL> fetchedUrls = Collections.synchronizedSet(new LinkedHashSet<URL>());
- private final LinkedBlockingQueue<URL> queue = new LinkedBlockingQueue<URL>();
+ private final LinkedBlockingQueue<URL> queue = new LinkedBlockingQueue<>();
public Crawler(OkHttpClient client) {
this.client = client;
@@ -81,33 +76,29 @@ public final class Crawler {
}
public void fetch(URL url) throws IOException {
- HttpURLConnection connection = client.open(url);
- String responseSource = connection.getHeaderField(OkHeaders.RESPONSE_SOURCE);
- String contentType = connection.getHeaderField("Content-Type");
- int responseCode = connection.getResponseCode();
+ Request request = new Request.Builder()
+ .url(url)
+ .build();
+ Response response = client.newCall(request).execute();
+ String responseSource = response.networkResponse() != null
+ ? ("(network: " + response.networkResponse().code() + ")")
+ : "(cache)";
+ int responseCode = response.code();
System.out.printf("%03d: %s %s%n", responseCode, url, responseSource);
- if (responseCode >= 400) {
- connection.getErrorStream().close();
- return;
- }
-
- InputStream in = connection.getInputStream();
+ String contentType = response.header("Content-Type");
if (responseCode != 200 || contentType == null) {
- in.close();
+ response.body().close();
return;
}
- MediaType mediaType = MediaType.parse(contentType);
- Document document = Jsoup.parse(in, mediaType.charset(UTF_8).name(), url.toString());
+ Document document = Jsoup.parse(response.body().string(), url.toString());
for (Element element : document.select("a[href]")) {
String href = element.attr("href");
URL link = parseUrl(url, href);
if (link != null) queue.add(link);
}
-
- in.close();
}
private URL parseUrl(URL url, String href) {
@@ -131,8 +122,8 @@ public final class Crawler {
long cacheByteCount = 1024L * 1024L * 100L;
OkHttpClient client = new OkHttpClient();
- HttpResponseCache httpResponseCache = new HttpResponseCache(new File(args[0]), cacheByteCount);
- client.setOkResponseCache(httpResponseCache);
+ Cache cache = new Cache(new File(args[0]), cacheByteCount);
+ client.setCache(cache);
Crawler crawler = new Crawler(client);
crawler.queue.add(new URL(args[1]));
diff --git a/samples/guide/pom.xml b/samples/guide/pom.xml
index 61e5875..1cc1b6a 100644
--- a/samples/guide/pom.xml
+++ b/samples/guide/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.squareup.okhttp.sample</groupId>
<artifactId>sample-parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
+ <version>2.3.0-SNAPSHOT</version>
</parent>
<artifactId>guide</artifactId>
@@ -18,5 +18,9 @@
<artifactId>okhttp</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
</dependencies>
</project>
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/guide/GetExample.java b/samples/guide/src/main/java/com/squareup/okhttp/guide/GetExample.java
index b5427c5..aa2f200 100644
--- a/samples/guide/src/main/java/com/squareup/okhttp/guide/GetExample.java
+++ b/samples/guide/src/main/java/com/squareup/okhttp/guide/GetExample.java
@@ -1,43 +1,25 @@
package com.squareup.okhttp.guide;
import com.squareup.okhttp.OkHttpClient;
-import java.io.ByteArrayOutputStream;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
import java.io.IOException;
-import java.io.InputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
public class GetExample {
OkHttpClient client = new OkHttpClient();
- void run() throws IOException {
- String result = get(new URL("https://raw.github.com/square/okhttp/master/README.md"));
- System.out.println(result);
- }
-
- String get(URL url) throws IOException {
- HttpURLConnection connection = client.open(url);
- InputStream in = null;
- try {
- // Read the response.
- in = connection.getInputStream();
- byte[] response = readFully(in);
- return new String(response, "UTF-8");
- } finally {
- if (in != null) in.close();
- }
- }
+ String run(String url) throws IOException {
+ Request request = new Request.Builder()
+ .url(url)
+ .build();
- byte[] readFully(InputStream in) throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- for (int count; (count = in.read(buffer)) != -1; ) {
- out.write(buffer, 0, count);
- }
- return out.toByteArray();
+ Response response = client.newCall(request).execute();
+ return response.body().string();
}
public static void main(String[] args) throws IOException {
- new GetExample().run();
+ GetExample example = new GetExample();
+ String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
+ System.out.println(response);
}
}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java b/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java
index 309ab70..5de644c 100644
--- a/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java
+++ b/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java
@@ -1,51 +1,26 @@
package com.squareup.okhttp.guide;
+import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
-import java.io.BufferedReader;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
public class PostExample {
- OkHttpClient client = new OkHttpClient();
-
- void run() throws IOException {
- byte[] body = bowlingJson("Jesse", "Jake").getBytes("UTF-8");
- String result = post(new URL("http://www.roundsapp.com/post"), body);
- System.out.println(result);
- }
+ public static final MediaType JSON
+ = MediaType.parse("application/json; charset=utf-8");
- String post(URL url, byte[] body) throws IOException {
- HttpURLConnection connection = client.open(url);
- OutputStream out = null;
- InputStream in = null;
- try {
- // Write the request.
- connection.setRequestMethod("POST");
- out = connection.getOutputStream();
- out.write(body);
- out.close();
-
- // Read the response.
- if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
- throw new IOException("Unexpected HTTP response: "
- + connection.getResponseCode() + " " + connection.getResponseMessage());
- }
- in = connection.getInputStream();
- return readFirstLine(in);
- } finally {
- // Clean up.
- if (out != null) out.close();
- if (in != null) in.close();
- }
- }
+ OkHttpClient client = new OkHttpClient();
- String readFirstLine(InputStream in) throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
- return reader.readLine();
+ String post(String url, String json) throws IOException {
+ RequestBody body = RequestBody.create(JSON, json);
+ Request request = new Request.Builder()
+ .url(url)
+ .post(body)
+ .build();
+ Response response = client.newCall(request).execute();
+ return response.body().string();
}
String bowlingJson(String player1, String player2) {
@@ -61,6 +36,9 @@ public class PostExample {
}
public static void main(String[] args) throws IOException {
- new PostExample().run();
+ PostExample example = new PostExample();
+ String json = example.bowlingJson("Jesse", "Jake");
+ String response = example.post("http://www.roundsapp.com/post", json);
+ System.out.println(response);
}
}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/AccessHeaders.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/AccessHeaders.java
new file mode 100644
index 0000000..9fe9d1a
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/AccessHeaders.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+
+public final class AccessHeaders {
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("https://api.github.com/repos/square/okhttp/issues")
+ .header("User-Agent", "OkHttp Headers.java")
+ .addHeader("Accept", "application/json; q=0.5")
+ .addHeader("Accept", "application/vnd.github.v3+json")
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println("Server: " + response.header("Server"));
+ System.out.println("Date: " + response.header("Date"));
+ System.out.println("Vary: " + response.headers("Vary"));
+ }
+
+ public static void main(String... args) throws Exception {
+ new AccessHeaders().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/AsynchronousGet.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/AsynchronousGet.java
new file mode 100644
index 0000000..34cfc58
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/AsynchronousGet.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Callback;
+import com.squareup.okhttp.Headers;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+
+public final class AsynchronousGet {
+ 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(Request request, IOException e) {
+ e.printStackTrace();
+ }
+
+ @Override public void onResponse(Response response) throws IOException {
+ 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(response.body().string());
+ }
+ });
+ }
+
+ public static void main(String... args) throws Exception {
+ new AsynchronousGet().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/Authenticate.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/Authenticate.java
new file mode 100644
index 0000000..44581ae
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/Authenticate.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Authenticator;
+import com.squareup.okhttp.Credentials;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.net.Proxy;
+
+public final class Authenticate {
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ client.setAuthenticator(new Authenticator() {
+ @Override public Request authenticate(Proxy proxy, Response response) {
+ System.out.println("Authenticating for response: " + response);
+ System.out.println("Challenges: " + response.challenges());
+ String credential = Credentials.basic("jesse", "password1");
+ return response.request().newBuilder()
+ .header("Authorization", credential)
+ .build();
+ }
+
+ @Override public Request authenticateProxy(Proxy proxy, Response response) {
+ return null; // Null indicates no attempt to authenticate.
+ }
+ });
+
+ Request request = new Request.Builder()
+ .url("http://publicobject.com/secrets/hellosecret.txt")
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new Authenticate().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/CacheResponse.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CacheResponse.java
new file mode 100644
index 0000000..3335ebe
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CacheResponse.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Cache;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.File;
+import java.io.IOException;
+
+public final class CacheResponse {
+ 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();
+ client.setCache(cache);
+ }
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("http://publicobject.com/helloworld.txt")
+ .build();
+
+ Response response1 = client.newCall(request).execute();
+ if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);
+
+ String 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());
+
+ Response response2 = client.newCall(request).execute();
+ if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);
+
+ String 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));
+ }
+
+ public static void main(String... args) throws Exception {
+ new CacheResponse(new File("CacheResponse.tmp")).run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/CancelCall.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CancelCall.java
new file mode 100644
index 0000000..9f8d373
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CancelCall.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Call;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+public class CancelCall {
+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
+ .build();
+
+ final long startNanos = System.nanoTime();
+ final Call call = client.newCall(request);
+
+ // Schedule a job to cancel the call in 1 second.
+ executor.schedule(new Runnable() {
+ @Override public void run() {
+ System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
+ call.cancel();
+ System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
+ }
+ }, 1, TimeUnit.SECONDS);
+
+ try {
+ System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
+ Response response = call.execute();
+ System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
+ (System.nanoTime() - startNanos) / 1e9f, response);
+ } catch (IOException e) {
+ System.out.printf("%.2f Call failed as expected: %s%n",
+ (System.nanoTime() - startNanos) / 1e9f, e);
+ }
+ }
+
+ public static void main(String... args) throws Exception {
+ new CancelCall().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/CertificatePinning.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CertificatePinning.java
new file mode 100644
index 0000000..b643d52
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CertificatePinning.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.CertificatePinner;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.security.cert.Certificate;
+
+public final class CertificatePinning {
+ private final OkHttpClient client;
+
+ public CertificatePinning() {
+ client = new OkHttpClient();
+ client.setCertificatePinner(
+ new CertificatePinner.Builder()
+ .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=")
+ .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
+ .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
+ .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")
+ .build());
+ }
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("https://publicobject.com/robots.txt")
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ for (Certificate certificate : response.handshake().peerCertificates()) {
+ System.out.println(CertificatePinner.pin(certificate));
+ }
+ }
+
+ public static void main(String... args) throws Exception {
+ new CertificatePinning().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/CheckHandshake.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CheckHandshake.java
new file mode 100644
index 0000000..0a2e86e
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/CheckHandshake.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.CertificatePinner;
+import com.squareup.okhttp.Interceptor;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.security.cert.Certificate;
+import java.util.Collections;
+import java.util.Set;
+
+public final class CheckHandshake {
+ /** Rejects otherwise-trusted certificates. */
+ private static final Interceptor CHECK_HANDSHAKE_INTERCEPTOR = new Interceptor() {
+ Set<String> blacklist = Collections.singleton("sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=");
+
+ @Override public Response intercept(Chain chain) throws IOException {
+ for (Certificate certificate : chain.connection().getHandshake().peerCertificates()) {
+ String pin = CertificatePinner.pin(certificate);
+ if (blacklist.contains(pin)) {
+ throw new IOException("Blacklisted peer certificate: " + pin);
+ }
+ }
+ return chain.proceed(chain.request());
+ }
+ };
+
+ private final OkHttpClient client = new OkHttpClient();
+
+ public CheckHandshake() {
+ client.networkInterceptors().add(CHECK_HANDSHAKE_INTERCEPTOR);
+ }
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("https://publicobject.com/helloworld.txt")
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new CheckHandshake().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/ConfigureTimeouts.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/ConfigureTimeouts.java
new file mode 100644
index 0000000..f358a45
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/ConfigureTimeouts.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.util.concurrent.TimeUnit;
+
+public final class ConfigureTimeouts {
+ private final OkHttpClient client;
+
+ public ConfigureTimeouts() throws Exception {
+ client = new OkHttpClient();
+ client.setConnectTimeout(10, TimeUnit.SECONDS);
+ client.setWriteTimeout(10, TimeUnit.SECONDS);
+ client.setReadTimeout(30, TimeUnit.SECONDS);
+ }
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
+ .build();
+
+ Response response = client.newCall(request).execute();
+ System.out.println("Response completed: " + response);
+ }
+
+ public static void main(String... args) throws Exception {
+ new ConfigureTimeouts().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/LoggingInterceptors.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/LoggingInterceptors.java
new file mode 100644
index 0000000..d70f107
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/LoggingInterceptors.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Interceptor;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.util.logging.Logger;
+
+public final class LoggingInterceptors {
+ private static final Logger logger = Logger.getLogger(LoggingInterceptors.class.getName());
+ private final OkHttpClient client = new OkHttpClient();
+
+ public LoggingInterceptors() {
+ client.networkInterceptors().add(new Interceptor() {
+ @Override public Response intercept(Chain chain) throws IOException {
+ long t1 = System.nanoTime();
+ Request request = chain.request();
+ logger.info(String.format("Sending request %s on %s%n%s",
+ request.url(), chain.connection(), request.headers()));
+ Response response = chain.proceed(request);
+
+ long t2 = System.nanoTime();
+ logger.info(String.format("Received response for %s in %.1fms%n%s",
+ request.url(), (t2 - t1) / 1e6d, response.headers()));
+ return response;
+ }
+ });
+ }
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("https://publicobject.com/helloworld.txt")
+ .build();
+
+ Response response = client.newCall(request).execute();
+ response.body().close();
+ }
+
+ public static void main(String... args) throws Exception {
+ new LoggingInterceptors().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/ParseResponseWithGson.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/ParseResponseWithGson.java
new file mode 100644
index 0000000..cf63f0d
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/ParseResponseWithGson.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.google.gson.Gson;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.util.Map;
+
+public final class ParseResponseWithGson {
+ private final OkHttpClient client = new OkHttpClient();
+ private final Gson gson = new Gson();
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("https://api.github.com/gists/c2a7c39532239ff261be")
+ .build();
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
+ for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
+ System.out.println(entry.getKey());
+ System.out.println(entry.getValue().content);
+ }
+ }
+
+ static class Gist {
+ Map<String, GistFile> files;
+ }
+
+ static class GistFile {
+ String content;
+ }
+
+ public static void main(String... args) throws Exception {
+ new ParseResponseWithGson().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/PerCallSettings.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PerCallSettings.java
new file mode 100644
index 0000000..af4956e
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PerCallSettings.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+
+public final class PerCallSettings {
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
+ .build();
+
+ try {
+ OkHttpClient cloned = client.clone(); // Clone to make a customized OkHttp for this request.
+ cloned.setReadTimeout(500, TimeUnit.MILLISECONDS);
+
+ Response response = cloned.newCall(request).execute();
+ System.out.println("Response 1 succeeded: " + response);
+ } catch (IOException e) {
+ System.out.println("Response 1 failed: " + e);
+ }
+
+ try {
+ OkHttpClient cloned = client.clone(); // Clone to make a customized OkHttp for this request.
+ cloned.setReadTimeout(3000, TimeUnit.MILLISECONDS);
+
+ Response response = cloned.newCall(request).execute();
+ System.out.println("Response 2 succeeded: " + response);
+ } catch (IOException e) {
+ System.out.println("Response 2 failed: " + e);
+ }
+ }
+
+ public static void main(String... args) throws Exception {
+ new PerCallSettings().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostFile.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostFile.java
new file mode 100644
index 0000000..a0d98df
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostFile.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
+import java.io.File;
+import java.io.IOException;
+
+public final class PostFile {
+ 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();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new PostFile().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostForm.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostForm.java
new file mode 100644
index 0000000..30054f1
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostForm.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.FormEncodingBuilder;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+
+public final class PostForm {
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ RequestBody formBody = new FormEncodingBuilder()
+ .add("search", "Jurassic Park")
+ .build();
+ Request request = new Request.Builder()
+ .url("https://en.wikipedia.org/w/index.php")
+ .post(formBody)
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new PostForm().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java
new file mode 100644
index 0000000..8e5334a
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.MultipartBuilder;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
+import java.io.File;
+import java.io.IOException;
+
+public final class PostMultipart {
+ /**
+ * The imgur client ID for OkHttp recipes. If you're using imgur for anything
+ * other than running these examples, please request your own client ID!
+ * https://api.imgur.com/oauth2
+ */
+ private static final String IMGUR_CLIENT_ID = "9199fdef135c122";
+ private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
+
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
+ RequestBody requestBody = new MultipartBuilder()
+ .type(MultipartBuilder.FORM)
+ .addFormDataPart("title", "Square Logo")
+ .addFormDataPart("image", null,
+ RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
+ .build();
+
+ Request request = new Request.Builder()
+ .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
+ .url("https://api.imgur.com/3/image")
+ .post(requestBody)
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new PostMultipart().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostStreaming.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostStreaming.java
new file mode 100644
index 0000000..500344c
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostStreaming.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import okio.BufferedSink;
+
+public final class PostStreaming {
+ 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();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new PostStreaming().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostString.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostString.java
new file mode 100644
index 0000000..943636a
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostString.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+
+public final class PostString {
+ 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();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new PostString().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/RequestBodyCompression.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/RequestBodyCompression.java
new file mode 100644
index 0000000..c4805bd
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/RequestBodyCompression.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.google.gson.Gson;
+import com.squareup.okhttp.Interceptor;
+import com.squareup.okhttp.MediaType;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.RequestBody;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import okio.BufferedSink;
+import okio.GzipSink;
+import okio.Okio;
+
+public final class RequestBodyCompression {
+ /**
+ * The Google API KEY for OkHttp recipes. If you're using Google APIs for anything other than
+ * running these examples, please request your own client ID!
+ * https://console.developers.google.com/project
+ */
+ public static final String GOOGLE_API_KEY = "AIzaSyAx2WZYe0My0i-uGurpvraYJxO7XNbwiGs";
+ public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");
+
+ private final OkHttpClient client = new OkHttpClient();
+
+ public RequestBodyCompression() {
+ client.interceptors().add(new GzipRequestInterceptor());
+ }
+
+ public void run() throws Exception {
+ Map<String, String> requestBody = new LinkedHashMap<>();
+ requestBody.put("longUrl", "https://publicobject.com/2014/12/04/html-formatting-javadocs/");
+ RequestBody jsonRequestBody = RequestBody.create(
+ MEDIA_TYPE_JSON, new Gson().toJson(requestBody));
+ Request request = new Request.Builder()
+ .url("https://www.googleapis.com/urlshortener/v1/url?key=" + GOOGLE_API_KEY)
+ .post(jsonRequestBody)
+ .build();
+
+ Response response = client.newCall(request).execute();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(response.body().string());
+ }
+
+ public static void main(String... args) throws Exception {
+ new RequestBodyCompression().run();
+ }
+
+ /** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
+ static class GzipRequestInterceptor implements Interceptor {
+ @Override public Response intercept(Chain chain) throws IOException {
+ Request originalRequest = chain.request();
+ if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
+ return chain.proceed(originalRequest);
+ }
+
+ Request compressedRequest = originalRequest.newBuilder()
+ .header("Content-Encoding", "gzip")
+ .method(originalRequest.method(), gzip(originalRequest.body()))
+ .build();
+ return chain.proceed(compressedRequest);
+ }
+
+ private RequestBody gzip(final RequestBody body) {
+ return new RequestBody() {
+ @Override public MediaType contentType() {
+ return body.contentType();
+ }
+
+ @Override public long contentLength() {
+ return -1; // We don't know the compressed length in advance!
+ }
+
+ @Override public void writeTo(BufferedSink sink) throws IOException {
+ BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
+ body.writeTo(gzipSink);
+ gzipSink.close();
+ }
+ };
+ }
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/RewriteResponseCacheControl.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/RewriteResponseCacheControl.java
new file mode 100644
index 0000000..63f819e
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/RewriteResponseCacheControl.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Cache;
+import com.squareup.okhttp.Interceptor;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.File;
+import java.io.IOException;
+
+public final class RewriteResponseCacheControl {
+ /** Dangerous interceptor that rewrites the server's cache-control header. */
+ private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
+ @Override public Response intercept(Chain chain) throws IOException {
+ Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .header("Cache-Control", "max-age=60")
+ .build();
+ }
+ };
+
+ private final OkHttpClient client;
+
+ public RewriteResponseCacheControl(File cacheDirectory) throws Exception {
+ Cache cache = new Cache(cacheDirectory, 1024 * 1024);
+ cache.evictAll();
+
+ client = new OkHttpClient();
+ client.setCache(cache);
+ }
+
+ public void run() throws Exception {
+ for (int i = 0; i < 5; i++) {
+ System.out.println(" Request: " + i);
+
+ Request request = new Request.Builder()
+ .url("https://api.github.com/search/repositories?q=http")
+ .build();
+
+ if (i == 2) {
+ // Force this request's response to be written to the cache. This way, subsequent responses
+ // can be read from the cache.
+ System.out.println("Force cache: true");
+ client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
+ } else {
+ System.out.println("Force cache: false");
+ client.networkInterceptors().clear();
+ }
+
+ Response response = client.newCall(request).execute();
+ response.body().close();
+ if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+
+ System.out.println(" Network: " + (response.networkResponse() != null));
+ System.out.println();
+ }
+ }
+
+ public static void main(String... args) throws Exception {
+ new RewriteResponseCacheControl(new File("RewriteResponseCacheControl.tmp")).run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/SynchronousGet.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/SynchronousGet.java
new file mode 100644
index 0000000..6b4cecb
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/SynchronousGet.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2014 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.Headers;
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.IOException;
+
+public final class SynchronousGet {
+ private final OkHttpClient client = new OkHttpClient();
+
+ public void run() throws Exception {
+ Request request = new Request.Builder()
+ .url("https://publicobject.com/helloworld.txt")
+ .build();
+
+ 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());
+ }
+
+ public static void main(String... args) throws Exception {
+ new SynchronousGet().run();
+ }
+}
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/recipes/WebSocketEcho.java b/samples/guide/src/main/java/com/squareup/okhttp/recipes/WebSocketEcho.java
new file mode 100644
index 0000000..738191a
--- /dev/null
+++ b/samples/guide/src/main/java/com/squareup/okhttp/recipes/WebSocketEcho.java
@@ -0,0 +1,70 @@
+package com.squareup.okhttp.recipes;
+
+import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import com.squareup.okhttp.internal.ws.WebSocket;
+import com.squareup.okhttp.internal.ws.WebSocketCall;
+import com.squareup.okhttp.internal.ws.WebSocketListener;
+import java.io.IOException;
+import okio.Buffer;
+import okio.BufferedSource;
+
+import static com.squareup.okhttp.internal.ws.WebSocket.PayloadType;
+import static com.squareup.okhttp.internal.ws.WebSocket.PayloadType.BINARY;
+import static com.squareup.okhttp.internal.ws.WebSocket.PayloadType.TEXT;
+
+/**
+ * WARNING: This recipe is for an API that is not final and subject to change at any time!
+ */
+public final class WebSocketEcho implements WebSocketListener {
+ private void run() throws IOException {
+ OkHttpClient client = new OkHttpClient();
+
+ Request request = new Request.Builder()
+ .url("ws://echo.websocket.org")
+ .build();
+ WebSocketCall.newWebSocketCall(client, request).enqueue(this);
+
+ // Trigger shutdown of the dispatcher's executor so this process can exit cleanly.
+ client.getDispatcher().getExecutorService().shutdown();
+ }
+
+ @Override public void onOpen(WebSocket webSocket, Request request, Response response)
+ throws IOException {
+ webSocket.sendMessage(TEXT, new Buffer().writeUtf8("Hello..."));
+ webSocket.sendMessage(TEXT, new Buffer().writeUtf8("...World!"));
+ webSocket.sendMessage(BINARY, new Buffer().writeInt(0xdeadbeef));
+ webSocket.close(1000, "Goodbye, World!");
+ }
+
+ @Override public void onMessage(BufferedSource payload, PayloadType type) throws IOException {
+ switch (type) {
+ case TEXT:
+ System.out.println(payload.readUtf8());
+ break;
+ case BINARY:
+ System.out.println(payload.readByteString().hex());
+ break;
+ default:
+ throw new IllegalStateException("Unknown payload type: " + type);
+ }
+ payload.close();
+ }
+
+ @Override public void onPong(Buffer payload) {
+ System.out.println("PONG: " + payload.readUtf8());
+ }
+
+ @Override public void onClose(int code, String reason) {
+ System.out.println("CLOSE: " + code + " " + reason);
+ }
+
+ @Override public void onFailure(IOException e) {
+ e.printStackTrace();
+ }
+
+ public static void main(String... args) throws IOException {
+ new WebSocketEcho().run();
+ }
+}
diff --git a/samples/pom.xml b/samples/pom.xml
index 62d1240..6991fa9 100644
--- a/samples/pom.xml
+++ b/samples/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.squareup.okhttp</groupId>
<artifactId>parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
+ <version>2.3.0-SNAPSHOT</version>
</parent>
<groupId>com.squareup.okhttp.sample</groupId>
diff --git a/samples/simple-client/pom.xml b/samples/simple-client/pom.xml
index 93657e2..3ebf058 100644
--- a/samples/simple-client/pom.xml
+++ b/samples/simple-client/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.squareup.okhttp.sample</groupId>
<artifactId>sample-parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
+ <version>2.3.0-SNAPSHOT</version>
</parent>
<artifactId>simple-client</artifactId>
diff --git a/samples/simple-client/src/main/java/com/squareup/okhttp/sample/OkHttpContributors.java b/samples/simple-client/src/main/java/com/squareup/okhttp/sample/OkHttpContributors.java
index c6424e2..e616d41 100644
--- a/samples/simple-client/src/main/java/com/squareup/okhttp/sample/OkHttpContributors.java
+++ b/samples/simple-client/src/main/java/com/squareup/okhttp/sample/OkHttpContributors.java
@@ -3,10 +3,9 @@ package com.squareup.okhttp.sample;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.OkHttpClient;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
+import com.squareup.okhttp.Request;
+import com.squareup.okhttp.Response;
+import java.io.Reader;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@@ -27,12 +26,16 @@ public class OkHttpContributors {
OkHttpClient client = new OkHttpClient();
// Create request for remote resource.
- HttpURLConnection connection = client.open(new URL(ENDPOINT));
- InputStream is = connection.getInputStream();
- InputStreamReader isr = new InputStreamReader(is);
+ Request request = new Request.Builder()
+ .url(ENDPOINT)
+ .build();
+
+ // Execute the request and retrieve the response.
+ Response response = client.newCall(request).execute();
// Deserialize HTTP response to concrete type.
- List<Contributor> contributors = GSON.fromJson(isr, CONTRIBUTORS.getType());
+ Reader body = response.body().charStream();
+ List<Contributor> contributors = GSON.fromJson(body, CONTRIBUTORS.getType());
// Sort list by the most contributions.
Collections.sort(contributors, new Comparator<Contributor>() {
diff --git a/samples/static-server/pom.xml b/samples/static-server/pom.xml
index 70188c7..e3dc358 100644
--- a/samples/static-server/pom.xml
+++ b/samples/static-server/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.squareup.okhttp.sample</groupId>
<artifactId>sample-parent</artifactId>
- <version>2.0.0-SNAPSHOT</version>
+ <version>2.3.0-SNAPSHOT</version>
</parent>
<artifactId>static-server</artifactId>
diff --git a/samples/static-server/src/main/java/com/squareup/okhttp/sample/SampleServer.java b/samples/static-server/src/main/java/com/squareup/okhttp/sample/SampleServer.java
index cb0e24e..a2fd19d 100644
--- a/samples/static-server/src/main/java/com/squareup/okhttp/sample/SampleServer.java
+++ b/samples/static-server/src/main/java/com/squareup/okhttp/sample/SampleServer.java
@@ -16,6 +16,8 @@ import java.security.SecureRandom;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
+import okio.Buffer;
+import okio.Okio;
public class SampleServer extends Dispatcher {
private final SSLContext sslContext;
@@ -32,7 +34,7 @@ public class SampleServer extends Dispatcher {
MockWebServer server = new MockWebServer();
server.useHttps(sslContext.getSocketFactory(), false);
server.setDispatcher(this);
- server.play(port);
+ server.start(port);
}
@Override public MockResponse dispatch(RecordedRequest request) {
@@ -82,9 +84,9 @@ public class SampleServer extends Dispatcher {
.addHeader("content-type: " + contentType(path));
}
- private byte[] fileToBytes(File file) throws IOException {
- byte[] result = new byte[(int) file.length()];
- Util.readFully(new FileInputStream(file), result);
+ private Buffer fileToBytes(File file) throws IOException {
+ Buffer result = new Buffer();
+ result.writeAll(Okio.source(file));
return result;
}