各位在代码江湖摸爬滚打的少侠们!今天我们要修炼的是Square派镇派绝学——OkHttp!这货堪称HTTP界的瑞士军刀,能屈能伸,上能砍高性能,下能怼低延迟!准备好让你的网络请求快如御剑飞行了吗? 🚀
一、筑基篇:初识OkHttp
1.1 法宝祭炼(添加依赖)
// Gradle配置(Android/JVM通用)
implementation 'com.squareup.okhttp3:okhttp:4.12.0' // 2023最新稳定版
<!-- Maven配置 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
1.2 创建本命法宝(OkHttpClient)
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS) // 连接超时
.readTimeout(30, TimeUnit.SECONDS) // 读取超时
.writeTimeout(30, TimeUnit.SECONDS) // 写入超时
.build(); // 建议全局单例,功德+10086
二、金丹篇:基础请求术
2.1 GET请求(探查敌情)
Request request = new Request.Builder()
.url("https://api.example.com/data")
.header("User-Agent", "OkHttp-Discovery") // 伪装术
.get() // 可省略,默认GET
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String body = response.body().string(); // 响应体读取(注意:只能读一次!)
System.out.println("秘籍到手:" + body);
} else {
System.out.println("渡劫失败:" + response.code());
}
}
2.2 POST请求(传送物资)
// 构建JSON灵力包
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String json = "{\"name\":\"张无忌\",\"age\":20}";
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url("https://api.example.com/users")
.post(body)
.build();
// 发送请求(同上execute流程)
三、元婴篇:高级神通
3.1 异步请求(分身术)
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
System.out.println("异步成功:" + response.body().string());
}
}
@Override
public void onFailure(Call call, IOException e) {
System.err.println("渡劫失败:" + e.getMessage());
}
});
// 主线程继续修炼,不阻塞!
3.2 文件上传(乾坤大挪移)
// 构建multipart/form-data
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("name", "赵敏")
.addFormDataPart("avatar", "photo.jpg",
RequestBody.create(new File("avatar.jpg"), MediaType.parse("image/jpeg"))
.build();
Request request = new Request.Builder()
.url("https://api.example.com/upload")
.post(requestBody)
.build();
四、化神篇:拦截器(偷天换日)
4.1 日志拦截器(天眼通)
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)) // 打印完整请求信息
.build();
4.2 统一请求头(万法归一)
Interceptor headerInterceptor = chain -> {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", "Bearer your_token")
.header("App-Version", "1.0.0")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
};
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(headerInterceptor)
.build();
五、大乘篇:安全渡劫
5.1 HTTPS证书验证(金钟罩)
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager) // 自定义证书
.hostnameVerifier((hostname, session) -> true) // 慎用!仅测试环境
.build();
5.2 超时重试(不死之身)
client = client.newBuilder()
.retryOnConnectionFailure(true) // 自动重试
.addInterceptor(new RetryInterceptor(3)) // 自定义重试策略
.build();
// 自定义重试拦截器示例
static class RetryInterceptor implements Interceptor {
private int maxRetry;
public RetryInterceptor(int maxRetry) { this.maxRetry = maxRetry; }
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = null;
IOException exception = null;
for (int i = 0; i <= maxRetry; i++) {
try {
response = chain.proceed(request);
if (response.isSuccessful()) return response;
} catch (IOException e) {
exception = e;
}
}
throw exception;
}
}
六、飞升篇:性能优化
6.1 连接池(灵气循环)
ConnectionPool pool = new ConnectionPool(
5, // 最大空闲连接数
5, // 保持时间
TimeUnit.MINUTES);
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(pool)
.build();
6.2 响应缓存(过目不忘)
File cacheDir = new File("okhttp_cache");
int cacheSize = 10 * 1024 * 1024; // 10MB
Cache cache = new Cache(cacheDir, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.build();
渡劫飞升总结
- 核心心法:重用OkHttpClient实例(单例最佳)
- 必杀技:拦截器实现统一鉴权/日志/重试
- 安全守则:生产环境严格校验SSL证书
- 性能奥义:合理配置连接池+缓存
飞升后选择:
- 深度修炼:集成Retrofit实现REST API
- 跨界融合:搭配RxJava/Coroutine异步处理
- 开宗立派:封装公司内部网络请求SDK