kotlin 带API的Android HTTP标头

vaqhlq81  于 2022-11-30  发布在  Kotlin
关注(0)|答案(1)|浏览(160)

如果我想做一个请求和响应的帖子,头是用来做什么的?怎么可能在那里“保存”令牌?
我找不到任何好的解释。

tf7tbtn2

tf7tbtn21#

您可以使用Retrofit来调用API,将令牌存储到共享首选项中,并将公共头添加到OkhttpClient

val prefs = Prefs.getInstance();

        val httpClient = OkHttpClient.Builder()
        httpClient.addInterceptor { chain ->
            val original = chain.request()
            val request = original.newBuilder()
                .header("Authorization", prefs.token)
                .header("Accept", "application/json")
                .method(original.method, original.body)
                .build()
            chain.proceed(request)
        }
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        httpClient.addInterceptor(interceptor)

        val client = httpClient.build()

并使改造对象像这样

Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().setPrettyPrinting().create()
                )
            )
            .client(client).build()

相关问题