如何使用 okhttp 将 Api_KEY 添加到拦截器中

How to add Api_KEY into interceptor using okhttp

我有这项服务,我想将令牌作为 okhttp 中的拦截而不是作为参数传递给 @Header("MY_API_KEY")

这是我的服务代码

/**
     * Provides the [PHService]
     */
    fun provideService(): PHService {

        val logger = HttpLoggingInterceptor()
        logger.level = HttpLoggingInterceptor.Level.BASIC



        val client = OkHttpClient.Builder()
                .addInterceptor(logger)
                .build()

        return Retrofit.Builder()
                .baseUrl(BuildConfig.API_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(PHService::class.java)
    }

如何在此处为 header 授权添加拦截器?

这样添加

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", "MY_API_KEY"); // <-- this is the important line

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });


    httpClient.connectTimeout(30, TimeUnit.SECONDS);
    httpClient.readTimeout(30, TimeUnit.SECONDS);
    httpClient.addNetworkInterceptor(logging);

 OkHttpClient client = httpClient.build();

在 kotlin 中类似

 val logging = HttpLoggingInterceptor()
    logging.level = HttpLoggingInterceptor.Level.BODY

    val httpClient = OkHttpClient.Builder()
    httpClient.addInterceptor { chain ->
        val original = chain.request()

        // Request customization: add request headers
        val requestBuilder = original.newBuilder()
                .header("Authorization", "MY_API_KEY") // <-- this is the important line

        val request = requestBuilder.build()
        chain.proceed(request)
    }


    httpClient.connectTimeout(30, TimeUnit.SECONDS)
    httpClient.readTimeout(30, TimeUnit.SECONDS)

    httpClient.addNetworkInterceptor(logging)

 val okHttpClient=httpClient.build()

如果您希望在请求中添加 api_key 和 app_id 作为查询参数,使用 kotlin 中的改造和 OkHttp 拦截器。您可以按照以下步骤操作。这很有用,因此您不必在每个查询的每个请求中传递密钥:

const val E_BASE_URL = "https://api.example.com"
const val API_ID = "YourApiID"
const val API_KEY = "YourApiKey"

//Here you add your url interceptor
//"app_id" and "app_key" might be different, depending on your API
val api_interceptor = Interceptor {
        val originalRequest = it.request()
        val newHttpUrl = originalRequest.url.newBuilder()
            .addQueryParameter("app_id", API_ID)  
            .addQueryParameter("app_key", API_KEY)
            .build()
        val newRequest = originalRequest.newBuilder()
            .url(newHttpUrl)
            .build()
        it.proceed(newRequest)
    }
    
//Add the logger interceptor optional:
val logger = HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.BASIC) }

//Build your OkHttpClient - here you add the api_interceptor and logger
val clientHTTP = OkHttpClient().newBuilder()
    .addNetworkInterceptor(logger)  //optional
    .addNetworkInterceptor(api_interceptor)
    .build()

//Build your json converter - in this example MOSHI
val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()


//FINALLY build your retrofit 
val retrofitE = Retrofit.Builder()
    .client(clientHTTP)
    .baseUrl(E_BASE_URL)
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .build()


//You can now declare your interfaces with your REST methods as usual, for example GET which will return your object
interface RecipesService {
    @GET("search")
    suspend fun getRecipes(
        @Query("q") recipe: String,
    ): RecipeResponse
}

//Finally you create your object (Singleton in Java) which generates your service via lazy delegate
object RecipesAPI {
    val retrofitService: RecipesService by lazy {
        retrofitE.create(RecipesService::class.java)
    }
}

本例需要在最新版本中引入如下依赖:

com.squareup.retrofit2:retrofit
com.squareup.moshi:moshi-kotlin
com.squareup.retrofit2:converter-moshi
com.squareup.okhttp3:logging-interceptor