原文地址:
=============================我是华丽丽的分割线=========================================
方法
我们已经写了一些方法,演示如何解决OkHttp的常见问题。阅读后可以了解如何共同工作。复制和粘贴这些例子,这也是它们存在的价值。
同步GET
下载一个文件,打印它的头文件,并且以字符串形式打印出它的响应体。
对于小文档来说,响应体的string()方法是方便高效的。但是如果响应体比较大(大于1MiB),避免使用string()方法,因为该方法会将整个文档加载到内存中。遇到这种情况的时候,我们更倾向于把响应体处理为流。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://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());
}
异步GET
在工作者线程(子线程)中下载一个文件,并且响应体可读时调用回调方法。当响应体的头文件准备完毕后,回调方法才会被执行。读取响应体可能一直阻塞。目前OkHttp并没有提供异步APIs,让我们分开接收响应体。
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 {
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());
}
});
}
获取头文件
典型的HTTP头文件有点像Map<String,String>:每一个字段都有一个值或者没有值。但是一些头文件允许多个值,像Guava的Multimap。举个例子,对HTTP的响应体来说,它的协议规范(It's legal and comon)是支持多种Vary头文件的。OkHttp的APIs
尝试兼容这两种情况。
当读取响应体的头文件的时候,header(name)适用于name和value一对一的情况。如果name和value是一对多的关系,那么新的值会覆盖之前的值。使用方法addHeader(name,value)添加一个头文件(header),则不会移除已经存在的头文件(headers)。
当读取响应体的头文件的时候,header(name)方法返回的是最新的命名值。通常情况下这也是唯一的结果。如果没有值,那么header(name)就会返回null。想要把一个字段的所有值读取为一个集合的话,就需要使用headers(name)。
为了访问所有的头文件,需要使用支持角标索引的Headers类。
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"));
}
POST发送字符串
使用HTTP的POST方式发送一个请求体到服务器。这个例子将一个Markdown文档通过post方式发送到将Markdown读取为HTML格式的web服务器。因为全部请求体同时存在于内存中,在使用这个API的时候,避免发送太大(大于1MiB)的文档。
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());
}
POST发送流
这里我们通过POST方法以流的方式发送请求体。请求体的内容边写边生成(is generated as it's being written)。在这个例子中,流直接放入Okio的缓冲(库)。你的程序可能更倾向于使用OutputSteam,你可以通过B
ufferedSink.outputStream()获取到。
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());
}
POST发送一个文件
将文件作为请求体,即可实现。
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());
}
POST发送表格参数
使用FormBody.Builder创建请求体,就像HTML中的<form>标签一样。键和值使用HTML兼容形式的URL编码进行编码。
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();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
POST发布多部分请求
MultipartBody.Builder可以构建多个与HTML文件上传表单兼容的请求体。多个请求体中的每一部分本身就是一个请求体,并且能够钉子它们自己的头文件。如果出现这种情况,那么这些头文件应该描述部分请求体,比如说它的Content-Disposition。当Content-Length和Content-Type头文件可以获取到的时候,它们会被自动添加进来。
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();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
使用Gson解析JSON格式的响应体
Gson是一款转化JSON和Java对象的优秀API。在这里,我们用它来将一个JSON格式的响应体解码(参考Github上API)。
这里要注意,当解码响应体的时候,ResponseBody.charStream()使用了Content-Type响应体头文件来决定使用哪个字符集。默认是UTF-8.
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;
}
响应体缓存
为了缓存响应体,你需要指定可以写入、读取的缓存路径,并且限定缓存大小。缓存路径应该是私有的,以保证不受信任的应用不能读取到它的内容。
对于同一个缓存路径,同时拥有多个入口的做法是错误的。大多数的应用地方应该只调用new OkHttp()一次,配置缓存,在每个地方使用同一个实例。否则两个缓存实例会相互冲突,使响应体缓存失效,并且应用有可能崩溃。
对于所有的配置,响应体缓存使用HTTP头文件。你可以自己添加头文件,比如说Cache-Control:max-stale=3600,覆盖OkHttp的默认缓存。服务器配置了响应体应当被缓存多久,存放在响应体的头文件中,比如Cache-Control:max-age=9600。当然,有些时候我们需要强制使用缓存的响应体,或者强制使用网络响应体,抑或是强制使用可选Get验证的网络响应体。
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();
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));
}
为了防止使用缓存中的响应体,可以使用CacheControl.FORCE_NETWORK.为了防止使用网络响应体,可以使用CacheControl.FORCE_CACHE.警告:如果你使用FORCE_CACHE,并且响应体需要网络,PkHttp可能会返回504(不可满足的请求)的响应。
取消一个调用
使用Call.cancel(),可以立即停止一个进行中的调用。如果一个线程正在写入一个请求或者读取一个响应体,就会接收到IOException。当某个调用失去其必要性的时候,使用这个方法可以节省网络;举个例子,当你的用户离开某个应用层的。同步和异步的调用都可以被取消。
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);
}
}
超时
当请求无法访问的时候,使用超时去结束一个调用。网络分区取决于客户端的连通性问题,服务器的稳定性问题,或者二者之间的任意问题。OkHttp支持连接、读取和写入超时。
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();
Response response = client.newCall(request).execute();
System.out.println("Response completed: " + response);
}
每一个调用的配置
所有的HTTP客户端配置都在OkHttpClient中,包括代理设置,超时和缓存。当你需要单独设置某一个调用的配置,调用OkHttpClient.newBuilder()即可。该方法将会返回Builder实例,与原来的client共用同一个连接池、调度器和配置。在下面的例子中,我们设置了超时分别为500ms和3000ms的请求
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 {
// Copy to customize OkHttp for this request.
OkHttpClient copy = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build();
Response response = copy.newCall(request).execute();
System.out.println("Response 1 succeeded: " + response);
} catch (IOException e) {
System.out.println("Response 1 failed: " + e);
}
try {
// Copy to customize OkHttp for this request.
OkHttpClient copy = client.newBuilder()
.readTimeout(3000, TimeUnit.MILLISECONDS)
.build();
Response response = copy.newCall(request).execute();
System.out.println("Response 2 succeeded: " + response);
} catch (IOException e) {
System.out.println("Response 2 failed: " + e);
}
}
处理认证
OkHttp可以自动重试非认证请求。当一个响应码是401(没有认证)的时候,认证者请求提供认证证书。实现的时候,需要创建一个新的请求,其中要包括缺失的认证证书。如果没有可获取的认证证书,那么将跳过重试,并返回null。
使用Response.challenges()获取任何认证(authentication challenges)的规范和域。当填满一个基本的challenge,使用Credentials.basic(username,password)来编码请求
private final OkHttpClient client;
public Authenticate() {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override public Request authenticate(Route route, Response response) throws IOException {
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();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
当认证不起作用的时候,为了避免发生多次尝试,你可以通过返回null的方式放弃。举个例子,当这些已存在的认证证书已经尝试过了,你可能想要跳过重试。
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
当达到应用设置的尝试上限的时候,你也需要跳过重试。
if (responseCount(response) >= 3) {
return null; // If we've failed 3 times, give up.
}
上面的代码依赖于responseCount()方法:
private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
(翻译的有点着急,我汪在旁边撒娇卖萌不止< -- >抽空再次修改 )
==========================================我是华丽丽的分割线=======================================================
(此处应当有我汪的照片,来日一并补上)