【Android】OkHttp+Retrofit+Flow的简单使用

需求

实现一个简单的登录功能

实现

引入依赖
    //okhttp
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
    //retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

我们现在有这样一个Body 请求参数

{
    
    
   "name": "001"
}

当使用post请求之后,获取返回的数据

{
    
    
    "flag": "true"
}

当允许登录的话,这个值就是true

我们先创建两个数据Bean类

data class LoginBean(
    /**
     * 员工工号
     */
    val name: String
)

data class LoginReturnBean(
    /**
    * 返回数据解析
    */
    val flag: String
)

然后我们再创建一个密封类处理返回结果的分类

sealed class LoginResult<out T> {
    
    

    data class LoginSuccess<out T>(val data: T) : LoginResult<T>()
    
    data class LoginFail(val error: Throwable) : LoginResult<Nothing>()
}

我们再创建一个Retrofit+OkHttp的单例类

object RetrofitClient {
    
    

    private var retrofit: Retrofit? = null

    private const val BASE_URL = "http://"

    private fun getOkHttpClient(): OkHttpClient {
    
    
        val builder = OkHttpClient.Builder()
            .addInterceptor(LogInterceptor())
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)// 错误重连
        return builder.build()
    }

    private fun getRetrofit(ipStr: String): Retrofit {
    
    
        if (retrofit == null) {
    
    
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL + ipStr)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit!!
    }

    fun service(ipStr: String): ApiService {
    
    
        return getRetrofit(ipStr).create(ApiService::class.java)
    }
}

好了,接下来再创建一个API 接口

interface ApiService {
    
    

    @Headers("Content-Type: application/json;charset=utf-8")
    @POST("/login")
    suspend fun postLogin(
        @Body loginName: RequestBody
    ): Response<LoginReturnBean>

}

接下来我们使用Flow来请求

    private fun flowLogin(name: String): Flow<LoginResult<LoginReturnBean>> = flow {
    
    
        val gson = Gson().toJson(LoginBean(name))
        val requestBody = gson
            .toRequestBody("application/json; Accept: application/json".toMediaTypeOrNull())
        val postLoginResult =
            RetrofitClient.service("192.168.1.10:9999")
                .postLogin(requestBody)
        if (postLoginResult.isSuccessful) {
    
    
            val loginResult: LoginReturnBean = postLoginResult.body()!!
            emit(LoginResult.LoginSuccess(loginResult))
        } else {
    
    
            val errorLoginResult = postLoginResult.errorBody()
            emit(LoginResult.LoginFail(IOException(errorLoginResult?.string())))
        }
    }.catch {
    
     exception ->
        emit(LoginResult.LoginFail(exception))
    }.flowOn(Dispatchers.IO)

好了,接下来就是调用了

  fun login(name: String, dataResult: IDataResult<String>) {
    
    
        viewModelScope.launch {
    
    
            dataResult.start()
            flowLogin(name).collect {
    
     result ->
                if (result is LoginResult.LoginSuccess) {
    
    
                    val data = result.data
                    if (data.flag == "true") {
    
    
                        dataResult.success("登录成功")
                    } else {
    
    
                        dataResult.fail("登录失败")
                    }
                } else {
    
    
                    dataResult.fail("登录失败")
                }
            }
        }
    }

怎么样,是不是感觉跟Retrofit+Okhttp+Rxjava实现起来有点像,又有点不像…

猜你喜欢

转载自blog.csdn.net/qq_43358469/article/details/131581875