阿杰,我帮你整理一份 OkHttp3 使用详解,从概念、依赖、核心类、同步/异步请求,到常用拦截器和高级用法,清晰易懂。
一、OkHttp3 概念
- 作用:一个高效的 HTTP 客户端库,用于 Java/Android 网络请求。
- 特点:
- 支持 同步/异步 HTTP 请求
- 支持 HTTP/2、连接池、透明压缩
- 支持 拦截器(Interceptor)处理请求/响应
- 支持 WebSocket
二、添加依赖(Maven/Gradle)
Gradle
implementation 'com.squareup.okhttp3:okhttp:4.11.0'
Maven
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.11.0</version>
</dependency>
注意 OkHttp3 的包名是
okhttp3
,4.x 版本是 OkHttp3 的升级版本。
三、核心类介绍
类 | 说明 |
---|---|
OkHttpClient | HTTP 客户端,负责连接管理、缓存和拦截器 |
Request | 构建 HTTP 请求(GET/POST/PUT/DELETE) |
RequestBody | POST/PUT 请求的请求体 |
Response | HTTP 响应结果 |
Call | 表示一次请求,可执行同步或异步请求 |
Interceptor | 拦截器,可处理请求和响应 |
MediaType | 指定请求体的内容类型 |
四、基本使用
1. GET 请求(同步)
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
System.out.println(response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
}
2. GET 请求(异步)
Call call = client.newCall(request);
call.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()) {
System.out.println(response.body().string());
}
}
});
3. POST 请求
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String json = "{\"name\":\"Ajie\",\"age\":30}";
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url("https://api.example.com/users")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
五、常用拦截器
1. 日志拦截器
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
2. 自定义拦截器(添加请求头)
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", "Bearer TOKEN")
.build();
return chain.proceed(request);
})
.build();
六、连接超时和重试设置
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
七、高级用法
- 文件上传
File file = new File("path/to/file");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(file, MediaType.get("application/octet-stream")))
.build();
Request request = new Request.Builder()
.url("https://api.example.com/upload")
.post(requestBody)
.build();
- 文件下载
Response response = client.newCall(request).execute();
try (InputStream is = response.body().byteStream();
FileOutputStream fos = new FileOutputStream("file.zip")) {
byte[] buffer = new byte[2048];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
}
- WebSocket
Request request = new Request.Builder().url("wss://example.com/socket").build();
WebSocket ws = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onMessage(WebSocket webSocket, String text) {
System.out.println("Received: " + text);
}
});
八、总结
- 核心对象:
OkHttpClient
→ 客户端Request
→ 请求Response
→ 响应Call
→ 调用(同步/异步)
- 常用技巧:
- 日志调试用
HttpLoggingInterceptor
- 拦截器统一处理 Token、Headers
- 连接池 + 超时 + 重试设置保证高性能
- 日志调试用
- 应用场景:
- Android 网络请求
- Java 服务端调用第三方 API
- 文件上传下载、WebSocket 通信
发表回复