}
});
}
提取响应头(Accessing Headers)
通常,HTTP标头的工作方式类似于Map<String, String>:每个字段都有一个值或者没有值。但是一些头文件允许多个值,比如Guava的Multimap。例如:HTTP响应提供多个Vary响应头。OkHttp的API让这两种情况都适用。
在写请求头的时候,使用header(name, value)来设置唯一的name、value。如果存在现有值,则在添加新值之前将它们删除。使用addHeader(name, value)来添加一个头,而不必删除已经存在的头。
在读取响应头时,使用header(name)返回最后一次出现的name、value。通常情况这也是唯一的。如果不存在任何值,那么header(name)将会返回null。如果要读取字段所对应的所有值,请使用headers(name),它会返回一个列表。
如果要获取所有的Header,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();
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”));
}
}
Post方式提交String(Posting a String)
使用HTTP POST提交请求到服务。本示例提交了一个Markdown文档到Web服务,并以HTML方式来渲染Markdown。由于整个请求体同时位于内存中,因此请避免使用此API发布较大的文档(大于1MB)。
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方式提交流(Post Streaming)
在这里,我们将请求体以流的方式进行提交。请求体的内容由流写入产生。该示例直接流入Okis的BufferedSink。你的程序可能会使用OutputStream,你可以用BufferedSink.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();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
Post方式提交文件(Posting a File)
以文件作为请求体是十分简单的。
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方式提交表单(Posting form parameters)
使用FormBody.Builder来构建一个像HTML标签相同效果的请求体。键值对将使用与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();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
Post方式提交分块请求(Posting a multipart request)
Multipart.Builder可以构建复杂的请求体,与HTML文件上传形式兼容。多块请求体的每块请求都是一个请求体,并且可以定义它自己的请求头。这些请求头可以用来描述这些请求,例如它的Content-Disposition。如果Content-Length和Content-Type可用的话,它们将自动被添加到请求头中。
/**
-
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());
}
}
用Moshi解析Json响应(Parse a JSON Response With Moshi)
Moshi是一个便捷的API,用于在Json和Java对象之间进行转换(Json解析)。这里我们使用它来解析来自GitHub API的Json响应。
请注意,ResponseBody.charStream()使用Content-Type响应头来选择在解析响应体时使用哪个字符集。如果没有指定字符集,它默认为UTF-8。
private final OkHttpClient client = new OkHttpClient();
private final Moshi moshi = new Moshi.Builder().build();
private final JsonAdapter gistJsonAdapter = moshi.adapter(Gist.class);
public void run() throws Exception {
Request request = new Request.Builder()
.url(“https://api.github.com/gists/c2a7c39532239ff261be”)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Gist gist = gistJsonAdapter.fromJson(response.body().source());
for (Map.Entry<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)
要缓存响应,您需要一个可以读取和写入的缓存目录,以及缓存大小的限制。缓存目录应该是私有的,不信任的应用程序不应该能够读取其内容。
多个缓存同时访问相同的缓存目录是错误的。大多数应用程序应该只调用一次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();
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 Unsatisfiable Request响应。
取消一个Call(Canceling a Call)
使用Call.cancel()可以立即停止正在执行的Call。如果一个线程正在写入请求或者读取响应,将会引发IOException。当Call没有必要的时候,使用这个API来节省网络资源。例如当你的用户离开应用程序时,同步或异步的Call都可以取消。
你可以通过tags来同时取消多个请求。当你构建一个请求时,使用Request.Builder().tag(tag)来分配一个标签。之后你就可以用Call.cancel(tag)来取消所有带有这个tag的call。
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)
当没有响应时使用超时来结束Call。没有响应的原因可能是客户端连接问题、服务器可用性问题等等。OkHttp支持连接、读取和写入超时。
private final OkHttpClient client;
public ConfigureTimeouts() throws Exception {
client = new OkHttpClient.Builder()
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
![](https://i-blog.csdnimg.cn/blog_migrate/f15f0dd85f94bedf2c871903aa4a5e96.jpeg)
【附】相关架构及资料
往期Android高级架构资料、源码、笔记、视频。高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter全方面的Android进阶实践技术,群内还有技术大牛一起讨论交流解决问题。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
8L-1712292634744)]
[外链图片转存中…(img-Ve8oQVoe-1712292634745)]
[外链图片转存中…(img-ChJ7GCBX-1712292634745)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
![](https://i-blog.csdnimg.cn/blog_migrate/f15f0dd85f94bedf2c871903aa4a5e96.jpeg)
【附】相关架构及资料
[外链图片转存中…(img-rb9Gmmdb-1712292634746)]
[外链图片转存中…(img-unaZLPTL-1712292634746)]
往期Android高级架构资料、源码、笔记、视频。高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter全方面的Android进阶实践技术,群内还有技术大牛一起讨论交流解决问题。