OkHttp官方使用教程(2)

在这篇文章中,我将告诉你OkHttp常见的使用场景,以及如何解决OkHttp常见的问题,你需要了解这些并明白它们是如何在一起工作的。

同步Get请求(Synchronous Get)

下载一个文件,打印它的响应头,并以字符串形式打印它的响应体。

响应体中的string()方法对于小文档来说非常方便和高效。但是,如果响应体太大(超过1M),请避免使用string(),因为它会将整个文档加载到内存中,在这种情况下,应该使用流方式处理响应体。

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

}

}

异步Get请求(Asynchronous Get)

在工作线程下载文件,并在响应可读时进行回调,回调会在响应头准备就绪后开始进行。读取响应体时可能会阻塞当前线程。OkHttp目前不提供异步API来部分接收响应体。

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让这两种情况都适用。

在写请求头的时候,使用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。

写在最后

最后我想说:对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上上述的技术体系图相关的几十套腾讯、头条、阿里、美团等公司2021年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

相信它会给大家带来很多收获:

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
Call没有必要的时候,使用这个API来节省网络资源。例如当你的用户离开应用程序时,同步或异步的Call都可以取消。

你可以通过tags来同时取消多个请求。当你构建一个请求时,使用Request.Builder().tag(tag)来分配一个标签。之后你就可以用Call.cancel(tag)来取消所有带有这个tag的call。

写在最后

最后我想说:对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上上述的技术体系图相关的几十套腾讯、头条、阿里、美团等公司2021年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

相信它会给大家带来很多收获:

[外链图片转存中…(img-4YtOyvvK-1715795402270)]

[外链图片转存中…(img-MvS9IPYR-1715795402273)]

当程序员容易,当一个优秀的程序员是需要不断学习的,从初级程序员到高级程序员,从初级架构师到资深架构师,或者走向管理,从技术经理到技术总监,每个阶段都需要掌握不同的能力。早早确定自己的职业方向,才能在工作和能力提升中甩开同龄人。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值