基本使用
首先记得在build.gradle 和 配置文件分别加上依赖 和 网络权限
1
| implementation 'com.squareup.okhttp3:okhttp:4.8.1'
|
1
| <uses-permission android:name="android.permission.INTERNET"/>
|
OkHttp采用建造者模式设计,使用很方便
异步Get请求
- 构造Request对象;
- new OkHttpClient;
- 通过前两步中的对象构建Call对象;
- 通过Call#enqueue(Callback)方法来提交异步请求;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| String url = "http://wwww.baidu.com"; final Request request = new Request.Builder() .url(url) .get() .build();
OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { Log.d(TAG, "onFailure: "); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { Log.d(TAG, "onResponse: " + response.body().string()); } });
|
异步发起的请求会被加入到 Dispatcher 中的 runningAsyncCalls双端队列中通过线程池来执行。
同步Get请求
前面几个步骤和异步方式一样,只是最后一部是通过 Call#execute() 来提交请求,注意这种方式会阻塞调用线程,所以在Android中应放在子线程中执行,否则有可能引起ANR异常,Android3.0 以后已经不允许在主线程访问网络。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| String url = "http://wwww.baidu.com";
final Request request = new Request.Builder() .url(url) .get() .build();
OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request);
new Thread(new Runnable() { @Override public void run() { try { Response response = call.execute(); Log.d(TAG, "run:"+response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }).start();
|
POST方式提交String
这种方式与前面的区别就是在构造Request对象时,需要多构造一个RequestBody对象,用它来携带我们要提交的数据。在构造 RequestBody 需要指定MediaType,用于描述请求/响应 body 的内容类型,关于 MediaType 的更多信息可以查看 RFC 2045.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| String url = "http://wwww.baidu.com"; MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); String requestBody = "I am quanzi"; final Request request = new Request.Builder() .url(url) .post(RequestBody.Companion.create(requestBody,mediaType)) .build();
OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { Log.d(TAG, "onFailure: "); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { Log.d(TAG, "onResponse: " + response.body().string()); } });
|
POST方式提交流
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
| RequestBody requestBody = new RequestBody() { @Nullable @Override public MediaType contentType() { return MediaType.parse("text/x-markdown; charset=utf-8"); }
@Override public void writeTo(@NonNull BufferedSink bufferedSink) throws IOException { bufferedSink.writeUtf8("I am quanzi."); } };
Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(requestBody) .build();
OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { Log.d(TAG, "onFailure: "); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message()); Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { Log.d(TAG, headers.name(i) + ":" + headers.value(i)); } Log.d(TAG, "onResponse: " + response.body().string()); } });
|
POST方式提交文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); File file = new File("test.md"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.Companion.create(file,mediaType)) .build();
OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure: " + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message()); Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { Log.d(TAG, headers.name(i) + ":" + headers.value(i)); } Log.d(TAG, "onResponse: " + response.body().string()); } });
|
POST方式提交表单
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
| RequestBody requestBody = new FormBody.Builder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(requestBody) .build();
OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure: " + e.getMessage()); }
@Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message()); Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { Log.d(TAG, headers.name(i) + ":" + headers.value(i)); } Log.d(TAG, "onResponse: " + response.body().string()); } });
|
POST方式提交分块请求
MultipartBody 可以构建复杂的请求体,与HTML文件上传形式兼容。多块请求体中每块请求都是一个请求体,可以定义自己的请求头。这些请求头可以用来描述这块请求,例如它的 Content-Disposition 。如果 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 31 32
| String IMGUR_CLIENT_ID = "..."; MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
MultipartBody body = new MultipartBody.Builder("AaB03x") .setType(MultipartBody.FORM) .addPart( Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, "Square Logo")) .addPart( Headers.of("Content-Disposition", "form-data; name=\"image\""), 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(body) .build();
OkHttpClient client = new OkHttpClient(); Call call = client.newCall(request);
call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println(response.body().string()); } });
|
拦截器-interceptor
OkHttp的拦截器链可谓是其整个框架的精髓,用户可传入的 interceptor 分为两类:
①一类是全局的 interceptor,该类 interceptor 在整个拦截器链中最早被调用,通过 OkHttpClient.Builder#addInterceptor(Interceptor) 传入;
②另外一类是非网页请求的 interceptor ,这类拦截器只会在非网页请求中被调用,并且是在组装完请求之后,真正发起网络请求前被调用,所有的 interceptor 被保存在 List interceptors 集合中,按照添加顺序来逐个调用,具体可参考 RealCall#getResponseWithInterceptorChain() 方法。通过 OkHttpClient.Builder#addNetworkInterceptor(Interceptor) 传入;
这里举一个简单的例子,例如有这样一个需求,我要监控App通过 OkHttp 发出的所有原始请求,以及整个请求所耗费的时间,针对这样的需求就可以使用第一类全局的 interceptor 在拦截器链头去做。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class LoggingInterceptor implements Interceptor {
private static final String TAG = "LoggingInterceptor";
@NonNull @Override public Response intercept(@NonNull Chain chain) throws IOException { Request request = chain.request();
long startTime = System.currentTimeMillis(); Log.d(TAG, String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long endTime = System.nanoTime(); Log.d(TAG, String.format("Received response for %s in %.1fms%n%s", response.request().url(), (endTime - startTime) / 1e6d, response.headers()));
return response; }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor()) .build();
Request request = new Request.Builder() .url("http://www.publicobject.com/helloworld.txt") .header("User-Agent", "OkHttp Example") .build();
okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { Log.d(TAG, "onFailure: " + e.getMessage()); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { ResponseBody body = response.body(); if (body != null) { Log.d(TAG, "onResponse: " + body.string()); body.close(); } } });
|
其他
- 推荐让 OkHttpClient 保持单例,用同一个 OkHttpClient 实例来执行你的所有请求,因为每一个 OkHttpClient 实例都拥有自己的连接池和线程池,重用这些资源可以减少延时和节省资源,如果为每个请求创建一个 OkHttpClient 实例,显然就是一种资源的浪费。当然,也可以使用如下的方式来创建一个新的 OkHttpClient 实例,它们共享连接池、线程池和配置信息。
1 2 3 4
| OkHttpClient eagerClient = client.newBuilder() .readTimeout(500, TimeUnit.MILLISECONDS) .build(); Response response = eagerClient.newCall(request).execute();
|
- 每一个Call(其实现是RealCall)只能执行一次,否则会报异常,具体参见 RealCall#execute()