Kotlin Retrofit 网络请求

一、添加依赖:

复制代码
    //Retrofit 网络请求
    implementation("com.squareup.retrofit2:retrofit:2.3.0")
    implementation("com.squareup.retrofit2:converter-gson:2.3.0")//json转换

二、创建单例类:

复制代码
package com.example.buju.http

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * retrofit网络请求
 * */
object HiRetrofit {
    val client = OkHttpClient.Builder()// builder构造者设计模式
        .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
        .readTimeout(10, TimeUnit.SECONDS)// 读取超时
        .writeTimeout(10, TimeUnit.SECONDS)// 写超时
        .addInterceptor(LoggingInterceptor())// 自定义拦截器
        .build()

    private var retrofit:Retrofit = Retrofit.Builder() // Builder构造者设计模式
        .client(client)// 借助okhttp3创建的client
        .baseUrl("baseUrl")// 网络请求前面的公共地址
        .addConverterFactory(GsonConverterFactory.create())// 数据转换适配器
        .build()

    fun <T> create(clazz: Class<T>):T{
        return retrofit.create(clazz)
    }

}

三、创建网络请求Api:

复制代码
package com.example.buju.http

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

/**
 * retrofit网络请求定义Api
 * */
interface ApiService {
    // 根据用户id查询信息
    @GET(value = "user/query")
    fun queryUser(@Query(value="userId",encoded = true) userId:String):Call<HashMap<String,String>>

}

使用:

复制代码
   val apiService:ApiService = HiRetrofit.create(ApiService::class.java)
        apiService.queryUser("0001").enqueue(object:Callback<HashMap<String,String>>{
            override fun onResponse(
                call: Call<HashMap<String, String>>,
                response: Response<HashMap<String, String>>
            ) {
                Log.e("Retrofit",response.body()?.toString() ?:"不知道原因")
            }

            override fun onFailure(call: Call<HashMap<String, String>>, t: Throwable) {
               Log.e("Retrofit",t.message?:"不知道原因")
            }
        })
相关推荐
侃侃_天下15 小时前
最终的信号类
开发语言·c++·算法
叽哥15 小时前
Kotlin学习第 8 课:Kotlin 进阶特性:简化代码与提升效率
android·java·kotlin
echoarts15 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix16 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题16 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说16 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔17 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
Kapaseker17 小时前
每个Kotlin开发者应该掌握的最佳实践,第一趴
kotlin
我是菜鸟0713号17 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_17 小时前
QT(4)
开发语言·汇编·c++·qt·算法