首页 > 其他分享 >Android Kotlin Retrofit MVP网络请求封装(四)

Android Kotlin Retrofit MVP网络请求封装(四)

时间:2023-06-21 19:44:13浏览次数:35  
标签:MVP retrofit2 Kotlin http fun import Android null com

依赖

   implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.google.code.gson:gson:2.8.8'

    implementation 'com.squareup.okhttp3:okhttp:4.9.1'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
    implementation 'com.google.code.gson:gson:2.8.6'

    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
AndroidManifest.xml
  <uses-permission android:name="android.permission.INTERNET" />

上下文

package com.example.app

import android.app.Application
import android.content.Context


/**
 *@author: jst
 *@date:   2023/6/19 0000 18:01
 *@desc:   上下文
 */
class App : Application() {
    companion object {
        private var context: Context? = null
        fun getContext(): Context? {
            return context
        }
    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
    }


}

 

application中加
 android:name=".App"

新建http,entity软件包

http网络连接请求封装

entity 实体

在http中封装Result 回调类(接口返回类)

package com.example.app.http

/**
 *@author: jst
 *@date:   2023/6/19 0000 18:01
 *@desc:  回调数据
 */
class Result<T> {
    /*
    var errorMsg: String? = null
    var errorCode: String? = null
    var data: T? = null
     */
    var res: Int? = 0
    var msg: String? = null

}

在entity实体中封装UserBean

package com.example.app.entity

class UserBean {
}

在http中封装接口请求基本回调抽象类

package com.example.app.http

import android.util.Log
import android.widget.Toast
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.internal.EverythingIsNonNull
import java.net.UnknownHostException
import  com.example.app.App

/**
 *@author: jst
 *@date:   2023/6/19 0000 18:01
 *@desc:  接口请求基本回调
 */
abstract class SingleCallback<T : Result<*>?> :
    Callback<T> {
    override fun onResponse(
        call: Call<T>,
        response: Response<T>
    ) {
        val result = response.body()
        if (result == null) {
            onFailure("-99", "接口请求失败", null)
        } else {
            if (apiFailure(result)) {
                onFailure(result.msg, result.msg ?: "", result)
            } else {
                onSuccess(result)
            }
        }
    }

    @EverythingIsNonNull
    override fun onFailure(call: Call<T>, t: Throwable) {
        Log.e("SingleCallback", "onFailure: " + t.message, t)
        if (t is UnknownHostException) {
            onFailure("-99", "接口请求失败", null)
        } else if (!"socket closed".equals(t.localizedMessage, ignoreCase = true)
            && !"canceled".equals(t.localizedMessage, ignoreCase = true)
        ) {
            onFailure("-999", "接口请求失败", null)
        }
    }

    fun successCode(): Int {
        return 1
    }

    fun apiFailure(result: T?): Boolean {
        return result == null || successCode() != result.res
    }

    /**
     * 失败回调。默认已经将失败信息提示出来
     */
    fun onFailure(code: String?, message: String, response: T?) {
        Toast.makeText(App.getContext(), message, Toast.LENGTH_SHORT).show()

    }


    abstract fun onSuccess(response: T)

}

 

在http中封装请求工具类HttpHelper

package com.example.app.http

import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit


/**
 *@author: jst
 *@date:   2023/6/19 0000 18:01
 *@desc:  接口请求工具类
 */
class HttpHelper {
    companion object {
        private val BASE_URL = "https:www.baidu.com" //接口域名
        private var sHttpClient: OkHttpClient? = null
        private var sApi: Api? = null

        fun getHttpClient(): OkHttpClient? {
            if (sHttpClient == null) {
                synchronized(HttpHelper::class.java) {
                    if (sHttpClient == null) {
                        val builder = OkHttpClient.Builder()
                        /**
                         * 打印日志
                         */
                        var interceptor = HttpLoggingInterceptor()
                        interceptor.level = HttpLoggingInterceptor.Level.BODY
                        builder.addInterceptor(interceptor)
                        sHttpClient = builder
                            .callTimeout(40, TimeUnit.SECONDS)
                            .connectTimeout(40, TimeUnit.SECONDS)
                            .readTimeout(40, TimeUnit.SECONDS)
                            .writeTimeout(40, TimeUnit.SECONDS)
                            .build()
                    }
                }
            }
            return sHttpClient
        }

        fun getApi(): Api? {
            if (sApi == null) {
                synchronized(HttpHelper::class.java) {
                    if (sApi == null) {
                        val retrofit = createRetrofit(BASE_URL)
                        sApi = retrofit.create(Api::class.java)
                    }
                }
            }
            return sApi
        }

        private fun createRetrofit(baseUrl: String): Retrofit {
            val gsonBuilder = GsonBuilder()
            return Retrofit.Builder()
                .client(getHttpClient())
                .baseUrl(baseUrl)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
                .build()
        }
    }
}

 

在http中新建Api接口

package com.example.app.http

import com.example.app.entity.UserBean
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.http.*
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

/**
 *@author: jst
 *@date:   2023/6/19 0000 18:01
 *@desc:  接口
 */
interface  Api {
    /**
     * 登录
     */
    @POST("/api/PDA/Checkuseradmin")
    @FormUrlEncoded
    fun login(@Field("username") account: String, @Field("password") password: String): Call<Result<UserBean>>


    /**
     * 登录
     */
    @GET("/api/PDA/Checkuseradmin")
    fun loginS(@Query("username") username:String,@Query("password") password: String):Call<Result<UserBean>>



    /**
     * 退出
     */
    @GET("/user/logout/json")
    fun logout(): Call<kotlin.Result<String>>

}

在model 登录实现类中调接口实现登录

 

 HttpHelper.getApi()?.loginS(userName, password)
            ?.enqueue(object : SingleCallback<Result<UserBean>>() {
                override fun onSuccess(response: Result<UserBean>) {
                    if (1 == response.res) {
                        onLoginListener.onSuccess()
                    } else {
                        onLoginListener.onError()
                    }
                }
            })

 

 效果

 

标签:MVP,retrofit2,Kotlin,http,fun,import,Android,null,com
From: https://www.cnblogs.com/jstblog/p/17496970.html

相关文章

  • Android Kotlin 底部菜单栏
    LoginSuccessActivity布局<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tool......
  • Android强大的原生调试工具adb的常用命令
    ADB简介ADB(AndroidDebugBridge)是用于与Android设备进行通信和调试的命令行工具。以下是一些常用的ADB调试命令:常用命令列出链接的设备adbdevices:列出连接到计算机的Android设备列表。可以看到这里我连接了两个设备。进入设备的shell环境adbshell:进入设备的命令行shell......
  • Android Kotlin MVP 登录实现
    一:新建MVP软件包文件 activity_main.xml界面<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"......
  • 【车载开发】Android Automotive车载操作系统开发解密篇
    提到Android车载,我们应该都不陌生。传统的车载功能单一,无太多娱乐性,而随着智能化时代的发展,车载系统也被赋予了在系统中预装Android应用的能力,基于Android平台的车载信息娱乐系统——AndroidAutomotive应运而生。而今,包括BAT在内许多传统互联网企业纷纷布局手机产业,追逐新能源造......
  • 入一线大厂;Android程序员一定要做的事
    前言很多做Android开发的朋友们都知道,从15年开始,就不断的有人在唱衰Android,在某乎上,经常可以看到这种标题。如果没有一点迹象也就不会有这么多风声传出了,之前在某呼上看到有人说是因为15年培训班兴起,线下培训机构陆续开发线上课程。培训机构造就了一大批速成的初级Android开发进入......
  • Android开发优化的几点建议
    前言安卓开发大军浩浩荡荡,经过近十年的发展,Android技术优化日异月新,Android系统性能也已经非常流畅,可以在体验上完全媲美iOS。但是,到了各大厂商手里,改源码、自定义系统,使得Android原生系统变得鱼龙混杂,然后到了不同层次的开发工程师手里,因为技术水平的参差不齐,即使很多手机在跑分......
  • Android Bresenham 直线算法 让你的手势更丝滑
    Bresenham算法是一种用于绘制直线的算法,它通过在离散的像素点上进行逐步的迭代来绘制出近似直线。以下是一个示例代码,演示了如何使用Bresenham算法绘制直线:fundrawLine(x0:Int,y0:Int,x1:Int,y1:Int){valdx=Math.abs(x1-x0)valdy=Math.abs(y1-......
  • app直播源代码,Android中点击图片放大的简单方法
    app直播源代码,Android中点击图片放大的简单方法Java代码: publicvoidonThumbnailClick(Viewv){//finalAlertDialogdialog=newAlertDialog.Builder(this).create();//ImageViewimgView=getView();//dialog.setView(imgView);//dialog.show();  //全屏显示的......
  • 索然无味!Kotlin开发从入门到上天,一篇文章就搞定了!(万字长文)
    标题党?看起来可能有点标题党的意思,但我知道,不这样,你们可能看不到这篇。关于Kotlin相关记录,如果有意查看我的github,其超10w字(其中8w是代码吗,哈哈)。。为什么要学?在不牺牲性能或安全性的前提下,许多的Kotlin功能使代码比Java更加简洁易懂。Kotlin编译为字节码,因此其性能与Java一样好......
  • 百度内网《Android车载操作系统开发指南》惨遭泄漏,24小时删!!!
    软件定义汽车背景下,操作系统是汽车生态发展的灵魂。随着汽车电动化、智能化、网联化的发展,汽车操作系统已经成为车辆中重要的组成部分之一,一定程度上决定了车辆的安全性、舒适度、智能化水平和整体性能。而Android系统开源、免费应用资源多、应用UI/Lunch、操控等人机交互开发,易定......