OKHTTP(四) Recipes(使用方法)

Recipes

我们已经编写了一些使用方法,演示如何使用OkHttp解决常见问题。
仔细阅读它们,了解一切如何协同工作。自由剪切和粘贴这些例子;

Synchronous Get

下载文件,打印其标题,并将其响应正文打印为字符串。
响应体上的string()方法对于小文档来说非常方便有效。
但是如果响应体很大(大于1 MiB),请避免使用string(),因为它会将整个文档加载到内存中。在这种情况下,更喜欢将消息体作为流来处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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());
}
}

Asynchronous Get

在工作线程上下载文件,并在响应可读时回调。
回调是在响应头准备好之后进行的。
阅读响应正文可能仍会阻止。
OkHttp目前不提供异步API来接收部分响应主体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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());
}
}
});
}

Accessing Headers(访问标题)

通常,HTTP标头的工作方式类似于Map <String,String>:每个字段都有一个值或没有。
但是一些标题允许多个值,例如Guava的Multimap。
例如,HTTP响应提供多个Vary标头是合法且常见的。
OkHttp的API试图使两种情况都很舒适。

在编写请求标头时,使用标头(名称,值)将name的唯一出现设置为value。
如果存在现有值,则在添加新值之前将删除它们。
使用addHeader(name,value)添加标头而不删除已存在的标头。

读取响应标头时,使用标头(名称)返回最后一次出现的命名值。
通常这也是唯一的发生!
如果没有值,则header(name)将返回null。
要将所有字段的值作为列表读取,请使用标题(名称)。

要访问所有标头,请使用支持索引访问的Headers类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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();

try (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"));
}
}

Posting a String

使用HTTP POST将请求正文发送到服务。
此示例将markdown文档发布到将markdown呈现为HTML的Web服务。
由于整个请求主体同时在内存中,因此请避免使用此API发布大型(大于1 MiB)文档。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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());
}
}

Post a file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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());
}
}

Post Streaming

在这里,我们将请求主体作为流发布。
该请求正文的内容正在编写时生成。
此示例直接流入Okio缓冲接收器。
您的程序可能更喜欢OutputStream,您可以从BufferedSink.outputStream()获取它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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 form parameters

使用FormBody.Builder构建一个像HTML

标记一样工作的请求体。
名称和值将使用HTML兼容的表单URL编码进行编码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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());
}
}

Posting a multipart request

MultipartBody.Builder可以构建与HTML文件上载表单兼容的复杂请求主体。
多部分请求主体的每个部分本身都是一个请求主体,并且可以定义自己的头部。
如果存在,这些标题应描述零件主体,例如其内容 - 处置。
如果Content-Length和Content-Type标头可用,则会自动添加它们。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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 = "...";
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 MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
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();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}
}

Parse a JSON Response With Moshi(使用Moshi解析JSON响应)

Moshi是一个方便的API,用于在JSON和Java对象之间进行转换。
在这里,我们使用它来解码来自GitHub API的JSON响应。

请注意,ResponseBody.charStream()使用Content-Type响应头来选择在解码响应主体时使用哪个charset。
如果未指定charset,则默认为UTF-8。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private final OkHttpClient client = new OkHttpClient();
private final Moshi moshi = new Moshi.Builder().build();
private final JsonAdapter<Gist> 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<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;
}

Response Caching

要缓存响应,您需要一个可以读取和写入的缓存目录,以及缓存大小的限制。
缓存目录应该是私有的,不受信任的应用程序不应该能够读取其内容。

让多个缓存同时访问同一缓存目录是错误的。
大多数应用程序应该只调用一次新的OkHttpClient(),使用它们的缓存配置它,并在任何地方使用相同的实例。
否则,两个缓存实例将相互踩踏,破坏响应缓存,并可能导致程序崩溃。

响应缓存使用HTTP标头进行所有配置。
您可以添加请求标头,如Cache-Control:max-stale = 3600,OkHttp的缓存将遵循它们。
您的Web服务器使用自己的响应标头配置缓存响应的时间,例如Cache-Control:max-age = 9600。
有缓存标头可强制缓存响应,强制网络响应,或强制使用条件GET验证网络响应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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));
}

要阻止响应使用缓存,请使用CacheControl.FORCE_NETWORK。
要阻止它使用网络,请使用CacheControl.FORCE_CACHE。
警告:如果你使用FORCE_CACHE并且响应需要网络,OkHttp将返回504不满意的请求响应。

Canceling a Call

使用Call.cancel()立即停止正在进行的呼叫。
如果线程当前正在写入请求或读取响应,则它将收到IOException。
当不再需要呼叫时,使用它来保护网络;
例如,当您的用户导航离开应用程序时。
同步和异步调用都可以取消。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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);

System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
try (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);
}
}

Timeouts

当对等方无法访问时,使用超时来使呼叫失败。
网络分区可能是由于客户端连接问题,服务器可用性问题或其他任何问题。
OkHttp支持连接,读取和写入超时。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private final OkHttpClient client;

public ConfigureTimeouts() throws Exception {
client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
}

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();

try (Response response = client.newCall(request).execute()) {
System.out.println("Response completed: " + response);
}

Per-call Configuration

所有HTTP客户端配置都存在于OkHttpClient中,包括代理设置,超时和缓存。
当您需要更改单个调用的配置时,请调用OkHttpClient.newBuilder()。
这将返回与原始客户端共享相同连接池,调度程序和配置的构建器。
在下面的示例中,我们发出一个请求,其中500毫秒超时,另一个请求超时3000毫秒。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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();

// Copy to customize OkHttp for this request.
OkHttpClient client1 = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build();
try (Response response = client1.newCall(request).execute()) {
System.out.println("Response 1 succeeded: " + response);
} catch (IOException e) {
System.out.println("Response 1 failed: " + e);
}

// Copy to customize OkHttp for this request.
OkHttpClient client2 = client.newBuilder()
.readTimeout(3000, TimeUnit.MILLISECONDS)
.build();
try (Response response = client2.newCall(request).execute()) {
System.out.println("Response 2 succeeded: " + response);
} catch (IOException e) {
System.out.println("Response 2 failed: " + e);
}
}

Handling authentication(认证处理)

OkHttp可以自动重试未经身份验证的请求。
如果响应为401 Not Authorized,则要求Authenticator提供凭据。
实现应该构建包含缺少凭据的新请求。
如果没有可用的凭据,则返回null以跳过重试。

使用Response.challenges()来获取任何身份验证挑战的方案和领域。
在完成基本挑战时,使用Credentials.basic(用户名,密码)对请求标头进行编码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private final OkHttpClient client;

public Authenticate() {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if (response.request().header("Authorization") != null) {
return null; // Give up, we've already attempted to authenticate.
}

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();
}
})
.build();
}

public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/secrets/hellosecret.txt")
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}
}

为避免在身份验证不起作用时进行多次重试,您可以返回null以放弃。
例如,您可能希望在尝试这些确切凭据时跳过重试:

1
2
3
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}

当您达到应用程序定义的尝试限制时,您也可以跳过重试:

1
2
3
if (responseCount(response) >= 3) {
return null; // If we've failed 3 times, give up.
}

上面的代码依赖于这个responseCount()方法:

1
2
3
4
5
6
7
private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}