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?:"不知道原因")
            }
        })
相关推荐
fish_xk1 小时前
c++中的引用和数组
开发语言·c++
酒尘&4 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
冬夜戏雪4 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
xwill*4 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
咖啡の猫5 小时前
Python列表的查询操作
开发语言·python
quikai19815 小时前
python练习第三组
开发语言·python
JIngJaneIL6 小时前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
吃西瓜的年年6 小时前
1. 初识C语言
c语言·开发语言
CHANG_THE_WORLD7 小时前
Python 字符串全面解析
开发语言·python
不会c嘎嘎7 小时前
深入理解 C++ 异常机制:从原理到工程实践
开发语言·c++