Springboot中使用Retrofit

Retrofit官网

https://square.github.io/retrofit/

配置gradle

复制代码
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation ("com.squareup.retrofit2:retrofit:2.11.0")
    implementation ("com.squareup.retrofit2:converter-gson:2.11.0")

创建Client

Kotlin 复制代码
package  com.cn.securities.manager

import com.cn.securities.manager.MapClient.Companion.BASE_URL
import okhttp3.OkHttpClient
import org.springframework.stereotype.Component
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
import kotlin.properties.Delegates

/**
 *    @Author : Cook
 *    @Date   : 2024/12/16
 *    @Desc   :
 *    @Version:
 */
@Component
class RetrofitClient {
    /**
     * 创建okhttp相关对象
     */
    private var okHttpClient: OkHttpClient by Delegates.notNull()

    /**
     * 创建Retrofit相关对象
     */
    private var retrofit: Retrofit by Delegates.notNull()

    /**
     * create you ApiService
     * Create an implementation of the API endpoints defined by the `service` interface.
     */
    fun <T> create(service: Class<T>?): T {
        if (service == null) {
            throw RuntimeException("Api service is null!")
        }
        return retrofit.create(service)
    }

    companion object {
        private const val TAG = "RequestRetrofit"

        //减少资源消耗
        const val TIME_OUT = 2L
    }

    init {
        /**
         * 创建okhttp相关对象
         */

        val sslSocketFactory = getSSLSocketFactory()
        if (sslSocketFactory == null) {
            okHttpClient = OkHttpClient.Builder()

                .connectTimeout(TIME_OUT, TimeUnit.SECONDS) //超时时间
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build()
        } else {
            okHttpClient = OkHttpClient.Builder()

                .connectTimeout(TIME_OUT, TimeUnit.SECONDS) //超时时间
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .sslSocketFactory(sslSocketFactory, CustomTrustManager())
                .hostnameVerifier(getHostnameVerifier())
                .build()
        }

        retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL) //BaseUrl
            .client(okHttpClient) //请求的网络框架
            .addConverterFactory(GsonConverterFactory.create()) //解析数据格式
            .build()
    }

    private fun getSSLSocketFactory(): SSLSocketFactory? {
        var ssfFactory: SSLSocketFactory? = null
        try {
            val sc: SSLContext = SSLContext.getInstance("TLS")
            sc.init(null, arrayOf<TrustManager>(CustomTrustManager()), SecureRandom())
            ssfFactory = sc.socketFactory
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ssfFactory
    }

    class CustomTrustManager : X509TrustManager {


        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {

        }

        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {

        }

        override fun getAcceptedIssuers(): Array<X509Certificate> {
            return arrayOf()
        }

    }

    private fun getHostnameVerifier(): HostnameVerifier {
        return HostnameVerifier { _, _ -> true }
    }


}

和Android部分一致,使用Gson解析

创建Service

Kotlin 复制代码
package com.cn.securities.manager

import com.cn.securities.model.response.weather.WeatherResult
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

/**
 *    @Author : Cook
 *    @Date   : 2024/12/16
 *    @Desc   :
 *    @Version:
 */
interface MapNetService {
    companion object {
        const val BASE_URL = "https://api.map.baidu.com/"
    }

    @GET("weather/v1/?data_type=all&ak=")
    fun queryWeather(@Query("district_id") districtId: String): Call<WeatherResult>

    @GET("weather/v1/?data_type=all&ak=")
    suspend fun queryWeatherInfo(@Query("district_id") districtId: String): WeatherResult
}

同步或者异步请求

调用

Kotlin 复制代码
package com.cn.securities.service.impl

import com.cn.securities.manager.MapManager
import com.cn.securities.model.response.weather.Weather
import com.cn.securities.service.intf.MapService
import org.springframework.stereotype.Service

/**
 *    @Author : Cook
 *    @Date   : 2024/12/17
 *    @Desc   :
 *    @Version:
 */
@Service
class MapServiceImpl(private val mapManager: MapManager) : MapService {
    
    override fun drivingNavigation() {

    }

    override fun queryWeather(): Weather? {
        val call = mapManager.getService().queryWeather("222405")
        val weather = call.execute().body()?.let {
            return it.result
        }
        return weather
    }
}
相关推荐
Bryce李小白20 天前
Kotlin实现Retrofit风格的网络请求封装
网络·kotlin·retrofit
魑魅魍魉都是鬼20 天前
白玩 一 记录retrofit+okhttp+flow 及 kts的全局配置
okhttp·retrofit
消失的旧时光-194323 天前
Android网络框架封装 ---> Retrofit + OkHttp + 协程 + LiveData + 断点续传 + 多线程下载 + 进度框交互
android·网络·retrofit
CYRUS_STUDIO1 个月前
彻底搞懂 Retrofit:使用、封装与 Converter 原理
android·okhttp·retrofit
zhysunny1 个月前
Retrofit+RxJava:打造声明式REST客户端的艺术 —— 像点咖啡一样调用API
java·rxjava·retrofit
每次的天空3 个月前
Android-OkHttp与Retrofit学习总结
android·okhttp·retrofit
追随远方3 个月前
深入解析OkHttp与Retrofit:Android网络请求的黄金组合
android·okhttp·retrofit
人间有清欢3 个月前
Android开发补充内容
android·okhttp·rxjava·retrofit·hilt·jetpack compose
androidwork3 个月前
Kotlin Coroutine与Retrofit网络层构建指南
开发语言·kotlin·retrofit