You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio Java项目中调用Laravel API实现JSON解析及增删改查

安卓Java项目对接Laravel API实现增删改查操作指南

一、前期依赖与权限配置

首先在项目中引入所需依赖并配置网络权限:

  1. 打开模块级build.gradle文件,在dependencies块中添加如下依赖:
// OkHttp 网络请求库
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
// Gson JSON解析库
implementation 'com.google.code.gson:gson:2.10.1'

同步完成后,打开AndroidManifest.xml添加网络权限,同时开启明文请求支持(你的接口为HTTP协议,安卓9及以上默认禁止HTTP请求):

<!-- 网络访问权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<application
    ...
    android:usesCleartextTraffic="true">
    ...
</application>

二、创建数据实体类

创建和返回JSON结构对应的Post.java实体类,用于JSON序列化和解析:

import com.google.gson.annotations.SerializedName;

public class Post {
    private Integer id;
    @SerializedName("user_id")
    private String userId;
    @SerializedName("category_id")
    private String categoryId;
    private String title;
    private String content;
    private String excerpt;
    @SerializedName("thumbnail_path")
    private String thumbnailPath;
    private String status;
    @SerializedName("created_at")
    private String createdAt;
    @SerializedName("updated_at")
    private String updatedAt;

    // Gson解析需要空构造方法
    public Post() {}

    // 提交数据用构造方法,不需要id、创建/更新时间(后端自动生成)
    public Post(String userId, String categoryId, String title, String content, String excerpt, String thumbnailPath, String status) {
        this.userId = userId;
        this.categoryId = categoryId;
        this.title = title;
        this.content = content;
        this.excerpt = excerpt;
        this.thumbnailPath = thumbnailPath;
        this.status = status;
    }

    // 所有字段的getter、setter可通过Android Studio右键->Generate->Getter and Setter一键生成,此处省略
}

三、封装OkHttp单例

避免重复创建网络请求实例,提高性能:

import okhttp3.OkHttpClient;

public class OkHttpUtil {
    private static OkHttpClient instance;

    public static OkHttpClient getInstance() {
        if (instance == null) {
            synchronized (OkHttpUtil.class) {
                if (instance == null) {
                    instance = new OkHttpClient();
                }
            }
        }
        return instance;
    }
}

四、增删改查功能实现

注意:所有网络请求必须在子线程执行,更新UI时需要切回主线程。

1. GET 查询所有帖子

import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;

// 网络请求放在子线程
new Thread(() -> {
    try {
        Request request = new Request.Builder()
                .url("http://laravelmy.com/public/api/posts")
                .get()
                .build();
        Response response = OkHttpUtil.getInstance().newCall(request).execute();
        if (response.isSuccessful() && response.body() != null) {
            String json = response.body().string();
            // 解析JSON数组为List<Post>
            Type listType = new TypeToken<List<Post>>(){}.getType();
            List<Post> postList = new Gson().fromJson(json, listType);
            // 切回主线程更新UI
            runOnUiThread(() -> {
                // 此处可将数据赋值给列表控件等
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

2. POST 新增帖子

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.Gson;

new Thread(() -> {
    try {
        // 构造要提交的帖子数据
        Post newPost = new Post("6","7","新标题","新内容","摘要","缩略图路径","1");
        String json = new Gson().toJson(newPost);
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url("http://laravelmy.com/public/api/posts")
                .post(body)
                .build();
        Response response = OkHttpUtil.getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            runOnUiThread(() -> {
                // 新增成功的逻辑,比如提示、刷新列表
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

3. PUT 修改帖子

需要将待修改的帖子ID拼接在请求URL末尾,示例修改ID为1的帖子:

new Thread(() -> {
    try {
        Post updatePost = new Post("5","8","修改后的标题","修改后的内容","摘要","新缩略图路径","1");
        String json = new Gson().toJson(updatePost);
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url("http://laravelmy.com/public/api/posts/1")
                .put(body)
                .build();
        Response response = OkHttpUtil.getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            // 修改成功逻辑
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

4. DELETE 删除帖子

需要将待删除的帖子ID拼接在请求URL末尾,示例删除ID为5的帖子:

new Thread(() -> {
    try {
        Request request = new Request.Builder()
                .url("http://laravelmy.com/public/api/posts/5")
                .delete()
                .build();
        Response response = OkHttpUtil.getInstance().newCall(request).execute();
        if (response.isSuccessful()) {
            // 删除成功逻辑
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

补充说明

  • 实际使用时可以封装统一的回调接口,处理成功、失败的通用逻辑
  • 生产环境建议将接口升级为HTTPS协议,避免明文传输风险
  • 可以根据需求添加加载弹窗、失败重试、参数校验等交互优化

内容的提问来源于stack exchange,提问作者Md. Shahinur Islam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:24:02