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
}
}