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
    }
}
相关推荐
帅次21 天前
OkHttp深度解析:请求流程、分发器机制、拦截器工作及TCP连接复用
android·okhttp·android studio·rxjava·android jetpack·retrofit·android runtime
老码沉思录2 个月前
Android开发实战班 -网络编程 - Retrofit 网络请求 + OkHttp 使用详解
android·网络·retrofit
粤M温同学2 个月前
Android 使用Retrofit 以纯二进制文件流上传文件
android·retrofit
一名技术极客2 个月前
不好意思,HttpClient 该换了,来感受下Retrofit的魅力
java·retrofit
帅次4 个月前
解决 Android WebView 无法加载 H5 页面常见问题的实用指南
android·okhttp·gradle·binder·webview·retrofit·appcompat
追梦的鱼儿5 个月前
okhttp,retrofit,rxjava 是如何配合工作的 作用分别是什么
okhttp·rxjava·retrofit
愿相知5 个月前
【Android】最好用的网络库:Retrofit
网络·retrofit
要小鑫呐5 个月前
实际项目中,运用Retrofit和OkHttp调用其他项目接口
java·网络·okhttp·retrofit
江南一舟1106 个月前
TabLayout使用以及自定义tab标签
android·kotlin·retrofit