Android 使用 Gson + OkHttp 实现 API 的常规使用(个人心得)

学习笔记

一、依赖和权限的添加

  1. 网络权限

    在 Android 中进行网络请求时,必须声明权限,确保应用具有访问互联网的能力。

<uses-permission android:name="android.permission.INTERNET"/>

依赖项

确保在 build.gradle 中添加以下依赖:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'//OkHttp的依赖
    implementation 'com.google.code.gson:gson:2.8.9'  // Gson依赖
}

二、创建与 JSON 结构匹配的 POJO 类

根据你的 JSON 数据结构创建 Java 类(POJO 类),用于 GSON 解析:

{
    "reason": "success",
    "result": {
        "curpage": 1,
        "allnum": 3,
        "newslist": [
            {
                "id": "ea5caaa3dc77b80916f4e1d00367b52a",
                "ctime": "2024-11-22 10:11",
                "title": "Example News",
                "description": "",
                "source": "News Source",
                "picUrl": "",
                "url": "https://example.com"
            }
        ]
    },
    "error_code": 0
}

创建 POJO 类

public class XinWenPhoto {
    private String reason;
    private Result result;
    private int errorCode;
 
    // Getter 方法

    ..................//省略get方法,可选toSing()方法
 
    public static class Result {
        private int curpage;
        private int allnum;
        private List<NewsItem> newslist;
 
        // Getter 方法

        ..................//省略get方法,可选toSing()方法

 
        public List<NewsItem> getNewslist() {
            return newslist;
        }
    }
 
    public static class NewsItem {
        private String id;
        private String ctime;
        private String title;
        private String description;
        private String source;
        private String picUrl;
        private String url;
 
       // Getter 方法

        ..................//省略get方法,可选toSing()方法

    }
}

三、创建网络请求方法

使用 OkHttp 发起 HTTP 请求并利用 Gson 解析响应数据。

public class ApiClient {

    private static final String API_URL = "http://apis.juhe.cn/fapigx/internet_news/query";
    private static final String API_KEY = "your_api_key_here"; // 替换为实际的 API Key

    // 获取新闻数据的 API 请求方法
    public static void fetchNewsData(String keyword, final NewsCallback callback) {
        String url = API_URL + "?key=" + API_KEY + "&num=3&word=" + keyword;

        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();

        // 创建请求对象
        Request request = new Request.Builder()
                .url(url) // 设置请求 URL
                .get()    // 使用 GET 方法
                .build();

        // 发送请求并异步处理回调(enqueue)
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e.getMessage()); // 请求失败时的回调
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 获取响应的 JSON 字符串
                    String jsonResponse = response.body().string();

                    // 使用 Gson 解析 JSON 字符串为 ApiResponse 对象
                    Gson gson = new Gson();
                    ApiResponse apiResponse = gson.fromJson(jsonResponse, ApiResponse.class);

                    // 请求成功,调用回调方法传
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值