kotlin retrofit使用Interceptor @Headers @Get @Path实现将存在在Headers里的接口参数进行拼接
时间: 2025-01-25 22:14:39 浏览: 23
在Kotlin中使用Retrofit进行网络请求时,可以通过Interceptor、@Headers、@Get和@Path注解来实现将存在Headers里的接口参数进行拼接。以下是一个详细的步骤和示例代码:
- 定义接口:首先,定义一个接口来描述你的API请求。
import retrofit2.http.*
interface ApiService {
@Headers("Content-Type: application/json")
@GET("api/{path}")
suspend fun getData(
@Header("Authorization") authHeader: String,
@Path("path") path: String
): Response<YourDataClass>
}
- 创建Interceptor:创建一个Interceptor来拦截请求并添加自定义的Headers。
import okhttp3.Interceptor
import okhttp3.Response
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val newRequest = originalRequest.newBuilder()
.addHeader("Authorization", "Bearer your_token")
.build()
return chain.proceed(newRequest)
}
}
- 配置Retrofit:配置Retrofit实例,并添加自定义的Interceptor。
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val retrofit = Retrofit.Builder()
.baseUrl("https://your.api.base.url/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
- 使用接口:在代码中使用定义的接口进行网络请求。
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
try {
val response = apiService.getData("Bearer your_token", "your_path")
if (response.isSuccessful) {
val data = response.body()
println(data)
} else {
println("Request failed with code: ${response.code()}")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
在这个示例中,我们通过Interceptor将Authorization
Header添加到请求中,并通过@Header注解将Authorization
Header传递给接口方法。同时,使用@Path注解将路径参数传递给接口方法。
相关推荐

















