如果我想做一个请求和响应的帖子,头是用来做什么的?怎么可能在那里“保存”令牌?我找不到任何好的解释。
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()
1条答案
按热度按时间tf7tbtn21#
您可以使用Retrofit来调用API,将令牌存储到共享首选项中,并将公共头添加到OkhttpClient
并使改造对象像这样