当前位置: 首页 > news >正文

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

package  com.cn.securities.managerimport 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? = nulltry {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

package com.cn.securities.managerimport 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
}

同步或者异步请求

调用

package com.cn.securities.service.implimport 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}
}

http://www.lryc.cn/news/506750.html

相关文章:

  • Ubuntu中配置内网固定IP
  • ExcelVBA编程输出ColorIndex与对应颜色色谱
  • MySQL中in和exists的使用场景
  • 【多线程2】start 和 run 区别,终止线程,等待线程
  • 富途证券C++面试题及参考答案
  • Go使用sqlx操作MySQL完整指南
  • Python 爬取网页文字并保存为 txt 文件教程
  • 时间序列预测论文阅读和相关代码库
  • Mamba安装环境和使用,anaconda环境打包
  • SSH连接成功,但VSCode连接不成功
  • springboot结合AES和国密SM4进行接口加密
  • iOS在项目中设置 Dev、Staging 和 Prod 三个不同的环境
  • openeuler24.09 系统无需配置 docker 源即可安装 docker 和 docker-composer
  • Flask入门:打造简易投票系统
  • 日常思考笔记
  • 【JAVA】后台管理系统密码复杂度和修改密码处理
  • 微服务SpringCloud链路追踪之Micrometer+Zipkin
  • Quartz(2-Trigger)
  • 【微信小程序开发 - 3】:项目组成介绍
  • Leetcode 三角形最小路径和
  • DataOps驱动数据集成创新:Apache DolphinScheduler SeaTunnel on Amazon Web Services
  • Android Studio的笔记--BusyBox相关
  • MySQL 存储过程与函数:增强数据库功能
  • 网络安全(3)_安全套接字层SSL
  • Git 快速入门
  • AI学习记录 - 依据 minimind 项目入门
  • 数据结构----链表头插中插尾插
  • 设计模式-读书笔记
  • c语言----选择结构
  • KS曲线python实现