OkHttp官方使用教程(1)

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

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

}

}

每个call的配置(Per-call Configuration)

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

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

推荐学习资料


  • 脑图
    360°全方位性能调优


    《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
    (Per-call Configuration)

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

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

推荐学习资料


  • 脑图
    [外链图片转存中…(img-zHiny7iP-1715728015526)]
    [外链图片转存中…(img-ryGeZtPy-1715728015530)]
    [外链图片转存中…(img-t1WCwrN8-1715728015532)]
    《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值