2025.5.27
学习内容
1.添加 OkHttp 依赖:在app/build.gradle文件中添加 OkHttp 依赖:
groovy
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
然后同步项目。
2. 使用 OkHttp 发送请求:学习使用 OkHttp 发送 GET 和 POST 请求。以下是发送 GET 请求的示例:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.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 {
if (response.isSuccessful()) {
final String responseData = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
// 处理响应数据
textView.setText(responseData);
}
});
}
}
});
发送 POST 请求的示例:
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String json = "{"name":"张三","age":25}";
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url("https://api.example.com/submit")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
// 处理响应
});
拦截器与缓存:学习使用 OkHttp 的拦截器记录请求和响应信息,以及配置缓存以提高性能。例如,添加日志拦截器:
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
收获
掌握了 OkHttp 的基本使用方法,相比 HttpURLConnection,OkHttp 的 API 更加简洁易用,代码可读性更高。学会了发送 GET 和 POST 请求,以及处理异步响应。了解了拦截器和缓存的使用,拦截器可以帮助调试网络请求,缓存可以减少网络请求,提高 App 性能。

浙公网安备 33010602011771号