当前位置: 首页 > news >正文

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() {@Overridepublic void onFailure(Call call, IOException e) {callback.onFailure(e.getMessage()); // 请求失败时的回调}@Overridepublic 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);// 请求成功,调用回调方法传
http://www.lryc.cn/news/504364.html

相关文章:

  • WPF+MVVM案例实战与特效(三十九)- 深度剖析一个弧形进度条的实现
  • opencv——图片矫正
  • 前端核心知识总结
  • 【C语言】五子棋(c语言实现)
  • 【数据结构——查找】顺序查找(头歌实践教学平台习题)【合集】
  • Python的3D可视化库【vedo】2-1 (plotter模块) 绘制器的使用
  • 6.1 初探MapReduce
  • 【数模学习笔记】模糊综合评价
  • 【C语言】库函数常见的陷阱与缺陷(四):内存内容操作函数[1]--memcmp
  • jmeter CLI Mode 传参实现动态设置用户数
  • 数据库和SQL的基本概念
  • CSS系列(9)-- Transform 变换详解
  • 一些浅显易懂的IP小定义
  • C 语言动态爱心代码
  • 【Figma_01】Figma软件初始与使用
  • 【Python篇】PyQt5 超详细教程——由入门到精通(序篇)
  • day2 数据结构 结构体的应用
  • CSS 进阶教程:从定位到动画与布局
  • Nginx性能优化全方案:打造一个高效服务器
  • 详解Maven的setting配置文件中mirror和repository的区别
  • 框架模块说明 #07 API加密
  • 安卓BLE蓝牙开发经验分享
  • 后缀表达式有什么场景应用
  • 使用 Kubernetes 部署 Redis 主从及 Sentinel 高可用架构(未做共享存储版)
  • AI开发 - 用GPT写一个GPT应用的真实案例
  • C#—索引器
  • 杨振宁大学物理视频中黄色的字去掉(稳定简洁版本,四)
  • 排序算法(5):归并排序
  • Gate学习(7)引入体素源
  • 2024.12.14 TCP/IP 网络模型有哪几层?