安卓基础(Okhttp3)
1️⃣ 添加 OkHttp 依赖
📌 在 app/build.gradle
添加 OkHttp 依赖
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}
2️⃣ 发送 GET 请求
📌 发送一个 GET 请求
实例化okhttp客户端--->创建请求--->发送请求
import okhttp3.*;
import java.io.IOException;
public class OkHttpExample {
public static void main(String[] args) {
// 1. 创建 OkHttpClient(网络客户端)
OkHttpClient client = new OkHttpClient();
// 2. 构造请求(GET 请求)
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/todos/1") // 目标 URL
.build();
// 3. 发送请求(异步执行)
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("请求失败: " + e.getMessage()); // 请求失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseBody = response.body().string(); // 获取返回数据
System.out.println("请求成功: " + responseBody); // 打印数据
}
});
}
}
3️⃣ 发送 POST 请求
📌 使用 POST
发送 JSON 数据
实例化okhttp客户端--->创建json数据--->创建body(含有json数据)--->创建请求(含有body)--->发送请求
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
public class OkHttpPostExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// 1. 创建 JSON 数据
JSONObject json = new JSONObject();
json.put("title", "Hello OkHttp");
json.put("body", "This is a test post");
json.put("userId", 1);
// 2. 创建 RequestBody
RequestBody requestBody = RequestBody.create(
json.toString(),
MediaType.parse("application/json; charset=utf-8")
);
// 3. 创建请求(POST 请求)
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts")
.post(requestBody)
.build();
// 4. 发送请求(异步)
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("请求失败: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseBody = response.body().string();
System.out.println("请求成功: " + responseBody);
}
});
}
}
📌 实现 WebSocket 客户端(连接、发送消息、接收消息、关闭)
import okhttp3.*;
public class WebSocketExample {
public static void main(String[] args) {
// 1️⃣ 创建 OkHttpClient
OkHttpClient client = new OkHttpClient();
// 2️⃣ 创建 WebSocket 连接请求
Request request = new Request.Builder()
.url("wss://echo.websocket.org") // WebSocket 服务器地址
.build();
// 3️⃣ 创建 WebSocket 监听器
WebSocketListener listener = new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
System.out.println("✅ WebSocket 连接成功");
webSocket.send("Hello WebSocket!"); // 发送消息
}
@Override
public void onMessage(WebSocket webSocket, String text) {
System.out.println("📩 收到消息: " + text);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
System.out.println("❌ WebSocket 连接关闭: " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
System.out.println("⚠️ WebSocket 连接失败: " + t.getMessage());
}
};
// 4️⃣ 创建 WebSocket 连接
WebSocket webSocket = client.newWebSocket(request, listener);
// 5️⃣ 关闭 WebSocket 客户端(防止程序未终止)
client.dispatcher().executorService().shutdown();
}
}