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

Android Kotlin 请求方法代码

接口请求方法

POST 请求模板

package com.yourpackage.requestimport android.content.Context
import androidx.lifecycle.LifecycleOwner
import com.yourpackage.beans.RequestParams
import com.yourpackage.beans.ResponseData
import com.yourpackage.http.api.ApiDefine
import com.yourpackage.http.api.ApiRequest
import com.yourpackage.http.api.RequestResponse
import com.yourpackage.http.beans.Response
import com.yourpackage.http.utils.ToastyUtils
import com.eyinfo.android_pure_utils.utils.JsonUtils
import com.google.gson.Gson
import com.hjq.http.EasyHttp
import com.hjq.http.body.JsonRequestBody/*** POST请求模板* 用于发送带参数的POST请求并处理响应*/
class PostRequest {// 回调监听器var requestListener: RequestListener? = null// 回调接口定义interface RequestListener {fun onSuccess(data: List<ResponseData?>)}/*** 发送POST请求* @param context 上下文* @param lifecycleOwner 生命周期所有者* @param params 请求参数对象* @param isShowLoading 是否显示加载框* @param api 请求接口地址*/fun request(context: Context,lifecycleOwner: LifecycleOwner,params: RequestParams,isShowLoading: Boolean,api: String) {val apiDefine = ApiDefine(api)EasyHttp.post(lifecycleOwner).api(apiDefine).body(JsonRequestBody(JsonUtils.toJson(params))) // 将参数转为JSON.request(object : RequestResponse<Response<List<ResponseData?>>>(context, isShowLoading) {// 请求成功回调override fun onSuccess(response: Response<List<ResponseData?>>?) {// 打印请求参数和响应数据(调试用)println("请求参数: ${Gson().toJson(params)}")println("响应数据: ${Gson().toJson(response?.data)}")if (response?.code == ApiRequest.SUCCESS) {// 成功时回调response.data?.let { requestListener?.onSuccess(it) }} else {// 失败提示ToastyUtils.show(response?.message ?: "请求失败")}}// 网络请求失败回调override fun onHttpFail(throwable: Throwable) {super.onHttpFail(throwable)ToastyUtils.show(throwable.message)println("请求失败: ${throwable.message} : ${throwable.cause}")}})}
}

GET 请求模板

package com.yourpackage.requestimport android.content.Context
import androidx.lifecycle.LifecycleOwner
import com.yourpackage.beans.ResponseData
import com.yourpackage.http.api.ApiDefine
import com.yourpackage.http.api.ApiPaths
import com.yourpackage.http.api.ApiRequest
import com.yourpackage.http.api.RequestResponse
import com.yourpackage.http.beans.Response
import com.yourpackage.http.utils.ToastyUtils
import com.google.gson.Gson
import com.hjq.http.EasyHttp/*** GET请求模板* 用于发送无参数或URL参数的GET请求并处理响应*/
open class GetRequest {// 回调监听器open var requestListener: RequestListener? = null// 回调接口定义interface RequestListener {fun onSuccess(data: ResponseData?)}/*** 发送GET请求* @param context 上下文* @param lifecycleOwner 生命周期所有者* @param isShowLoading 是否显示加载框* @param api 请求接口地址(可从ApiPaths获取)*/fun request(context: Context,lifecycleOwner: LifecycleOwner,isShowLoading: Boolean,api: String) {val apiDefine = ApiDefine(api)EasyHttp.get(lifecycleOwner).api(apiDefine).request(object : RequestResponse<Response<ResponseData>>(context, isShowLoading) {// 请求成功回调override fun onSuccess(response: Response<ResponseData>?) {// 处理响应数据(如需要可保存到本地)response?.data?.let { // 示例:保存数据到SharedPreferences// UserSharedPreferencesUtils.getInstance().saveData(it.toString())}if (response?.code == ApiRequest.SUCCESS) {// 成功时回调requestListener?.onSuccess(response.data)}}// 网络请求失败回调override fun onHttpFail(throwable: Throwable) {super.onHttpFail(throwable)println("请求失败: ${throwable.message}")ToastyUtils.show("请求失败: ${throwable.message}")}})}
}

分页

分页数据模型类

import java.io.Serializableclass Pagination : Serializable {private var total = 0          // 总条数private var page = 0           // 当前页码private var pageSize = 0       // 每页条数fun getTotal(): Int = totalfun setTotal(total: Int?) {this.total = total ?: this.total}fun getPage(): Int = pagefun setPage(page: Int?) {this.page = page ?: this.page}fun getPageSize(): Int = pageSizefun setPageSize(pageSize: Int?) {this.pageSize = pageSize ?: this.pageSize}// 判断是否为最后一页fun isLastPage(): Boolean {return page * pageSize >= total}
}

分页处理器(核心控制类)

import com.eyinfo.android_pure_utils.utils.ObjectJudge
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayoutopen class PageHandler<Item> {private var currentPage: Int = 1      // 当前页码,默认从1开始private var pageSize: Int = 10        // 每页条数,默认10条private var items: MutableList<Item> = mutableListOf()  // 数据集合// Getter和Setter方法fun setPageSize(pageSize: Int) {this.pageSize = pageSize}fun setCurrentPage(currentPage: Int) {this.currentPage = currentPage}fun setItems(items: MutableList<Item>) {this.items = items}fun getItems(): MutableList<Item> = itemsfun getCurrentPage(): Int = currentPagefun getPageSize(): Int = pageSize// 刷新数据(重新加载第一页)fun refresh() {onRequestData(currentPage, pageSize)}// 子类实现具体的网络请求逻辑protected open fun onRequestData(currentPage: Int, pageSize: Int) {}// 注册刷新控件的监听事件fun registerListener(refreshLayout: RefreshLayout) {// 下拉刷新逻辑refreshLayout.setOnRefreshListener { layout ->currentPage = 1items.clear()onRequestData(currentPage, pageSize)layout.finishRefresh()  // 结束刷新动画}// 上拉加载更多逻辑refreshLayout.setOnLoadMoreListener { layout ->currentPage++onRequestData(currentPage, pageSize)layout.finishLoadMore()  // 结束加载动画}}// 判断是否为空数据(第一页无数据)fun isEmptyData(data: MutableList<Item?>?, pageNum: Int): Boolean {return pageNum == 1 && ObjectJudge.isNullOrEmpty(data)}// 处理加载完成的数据fun loadDone(refreshLayout: SmartRefreshLayout, pagination: Pagination, data: MutableList<Item?>) {val currentPage = pagination.getPage()val pageSize = pagination.getPageSize()// 如果是第一页,先清空原有数据if (currentPage == 1) {items.clear()this.currentPage = 1}// 添加新数据if (!ObjectJudge.isNullOrEmpty(data)) {items.addAll(data as Collection<Item>)// 如果返回的数据少于每页应有的数量,说明没有更多数据了if (data.size < pageSize) {refreshLayout.finishLoadMoreWithNoMoreData()}} else {// 没有数据了refreshLayout.finishLoadMoreWithNoMoreData()}}
}

在 Fragment 中使用分页的示例代码

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.creatorsaijs.creatorai.databinding.FragmentCenterTextLayoutBinding
import com.creatorsaijs.creatorai.fragment.BaseFragmentclass YourListFragment : BaseFragment() {private var binding: FragmentCenterTextLayoutBinding? = nullprivate lateinit var yourAdapter: YourListAdapter  // 你的适配器private val pageHandler: PageHandler<YourDataModel> = object : PageHandler<YourDataModel>() {override fun onRequestData(currentPage: Int, pageSize: Int) {super.onRequestData(currentPage, pageSize)// 构建请求参数val params = YourRequestParams()params.pageNumber = currentPageparams.pageSize = pageSize// 发起网络请求yourRequest.request(requireContext(), this@YourListFragment, params, true, yourApiPath)}}override fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)initRecyclerView()initPageHandler()initRequestListener()}private fun initRecyclerView() {binding?.recyclerView?.layoutManager = LinearLayoutManager(requireContext())yourAdapter = YourListAdapter(requireContext())yourAdapter.dataList = pageHandler.getItems()binding?.recyclerView?.adapter = yourAdapter}private fun initPageHandler() {// 注册刷新控件pageHandler.registerListener(binding?.refreshLayout!!)// 初始加载数据pageHandler.refresh()}private fun initRequestListener() {yourRequest.listener = object : YourRequestListener {override fun onSuccess(dataList: List<YourDataModel?>, pagination: Pagination) {// 处理空数据情况if (pageHandler.isEmptyData(dataList.toMutableList(), pagination.getPage())) {showEmptyView()  // 显示空数据提示} else {hideEmptyView()  // 隐藏空数据提示// 通知分页处理器数据加载完成pageHandler.loadDone(binding!!.refreshLayout, pagination, dataList.toMutableList())yourAdapter.notifyDataSetChanged()  // 刷新列表}}}}// 空数据显示控制private fun showEmptyView() {binding?.refreshLayout?.visibility = View.GONEbinding?.emptyView?.visibility = View.VISIBLE}private fun hideEmptyView() {binding?.refreshLayout?.visibility = View.VISIBLEbinding?.emptyView?.visibility = View.GONE}
}

文章转载自:

http://SUfwyQnO.Lzzqz.cn
http://5v1lwmWM.Lzzqz.cn
http://Sqcy0MOF.Lzzqz.cn
http://wv8YISrq.Lzzqz.cn
http://RhDA9YCs.Lzzqz.cn
http://B3HEAUG9.Lzzqz.cn
http://QPrmcBcX.Lzzqz.cn
http://QFtClVv7.Lzzqz.cn
http://ls0VpbI9.Lzzqz.cn
http://pNQauH85.Lzzqz.cn
http://DxuSuu5z.Lzzqz.cn
http://GlhVPwTe.Lzzqz.cn
http://6Hrp8po5.Lzzqz.cn
http://OdRZrc8Q.Lzzqz.cn
http://vX42Sysa.Lzzqz.cn
http://9Zrwdifd.Lzzqz.cn
http://1QOKNDJZ.Lzzqz.cn
http://T60cRwtN.Lzzqz.cn
http://iv6DEwY6.Lzzqz.cn
http://dBZK8kAF.Lzzqz.cn
http://iWgnN4Fg.Lzzqz.cn
http://WsYlkII7.Lzzqz.cn
http://eQEs3awi.Lzzqz.cn
http://21al2MKZ.Lzzqz.cn
http://SNedCah5.Lzzqz.cn
http://gFLmM9FS.Lzzqz.cn
http://0qvKg0Yb.Lzzqz.cn
http://AJzTzasS.Lzzqz.cn
http://pv1zTYNp.Lzzqz.cn
http://wVTXl0Ea.Lzzqz.cn
http://www.dtcms.com/a/387545.html

相关文章:

  • 【easy_tools】一个跨平台裸机工具库,包含任务/堆栈/消息/定时器/日志等实现
  • ARM(11) - LM75
  • FPGA实现SRIO数据回环传输,基于Serial Rapidlo Gen2架构,提供6套工程源码和技术支持
  • 第十九章 Arm C1-Premium TRBE技术解析
  • HTB writeup
  • 科学研究系统性思维的理论基础:数字化研究工具
  • 基于有限元-元胞自动机法(CAFE)的增材制造过程组织模拟
  • 电视行业复兴,数字化制造如何重塑“视界”新格局?
  • 从兼容到极致性能——qData数据中台商业版核心指标解读
  • MAC-枚举反射工具类
  • 搜索百科(1):Lucene —— 打开现代搜索世界的第一扇门
  • 学习日记-JS+DOM-day57-9.17
  • Java异常处理最佳实践指南
  • Ansible简介
  • pytest使用总结笔记
  • 在VSCode中设置Qt开发环境
  • 斜杠命令Slash Commands:Roo Code 的自动化利器
  • 大数据毕业设计选题推荐-基于大数据的慢性肾病数据可视化分析系统-Spark-Hadoop-Bigdata
  • 基于红尾鹰优化的LSTM深度学习网络模型(RTH-LSTM)的一维时间序列预测算法matlab仿真
  • TDengine IDMP 基本功能——数据可视化(2. 柱状图)
  • Python与Google Earth Engine (GEE) 实现地理空间数据自动化处理:高效分析与批量任务执行
  • Dify Agent + AntV 实战:从 0 到 1 打造数据可视化解决方案
  • 系统架构设计师备考第25天——软件测试
  • 十、vue3后台项目系列——登录页面的搭建
  • 在博主内容推送系统中,通过RabbitMQ异步解耦及消息持久化+重试机制,使推送效率提升300%,成功率提升至99.9%的原理及实现
  • 【FreeRTOS】二值信号量vs互斥量核心差异
  • 记一次golang结合前端的axios进行预签名分片上传遇到403签名错误踩坑
  • LeetCode 面试经典 150_哈希表_单词规律(41_290_C++_简单)
  • 微信小程序修改页面导航标题的方式
  • Torch-Rechub学习笔记-task1