安卓基础(Okhttp3)

1️⃣ 添加 OkHttp 依赖

📌 app/build.gradle 添加 OkHttp 依赖

java 复制代码
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}

2️⃣ 发送 GET 请求

📌 发送一个 GET 请求

实例化okhttp客户端--->创建请求--->发送请求

java 复制代码
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)--->发送请求

java 复制代码
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 客户端(连接、发送消息、接收消息、关闭)

java 复制代码
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();
    }
}
相关推荐
麦田里的守望者江39 分钟前
这个PC项目是去做还是不去做?
android·c++
宁子希44 分钟前
如何将 ESP32 快速接入高德、心知、和风天气API 获取天气信息
android·单片机·嵌入式硬件·esp32
V少年1 小时前
深入浅出Java线程池
android·java
顾林海1 小时前
深度解析Hashtable工作原理
android·java·面试
老板来根葱2 小时前
这一次,让SystemServer, SystemServiceManager,SystemService不可能再记混
android·源码阅读
鱼洗竹2 小时前
Flow 的操作符
android
张风捷特烈2 小时前
平面上的三维空间#05 | 几何形体
android·flutter
stevenzqzq10 小时前
android中dp和px的关系
android
一一Null12 小时前
Token安全存储的几种方式
android·java·安全·android studio
JarvanMo13 小时前
flutter工程化之动态配置
android·flutter·ios