You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发中使用Retrofit2如何在请求头添加API Key

Retrofit2 携带 Access-Key 请求的实现方案

方案1:单个接口单独配置

仅少数接口需要传 Key 时用这个方案,直接在接口方法加 @Header 注解:

public interface ApiService {
    @GET("你的实际接口路径")
    Call<自定义响应实体类> fetchData(@Header("Access-Key") String accessKey);
}

调用接口时传入对应 Key 值即可:

ApiService service = retrofit.create(ApiService.class);
Call<自定义响应实体类> call = service.fetchData("9xxxxxxxxxxxxx3");

方案2:全局统一配置

多数接口都需要传 Key 时用这个方案,通过 OkHttp 拦截器统一添加,无需每个接口单独配置:

  • 第一步:构建带拦截器的 OkHttpClient 实例
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(chain -> {
        Request original = chain.request();
        Request requestWithKey = original.newBuilder()
            .addHeader("Access-Key", "9xxxxxxxxxxxxx3")
            .build();
        return chain.proceed(requestWithKey);
    })
    .build();
  • 第二步:构建 Retrofit 实例时传入自定义的 OkHttpClient
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("你的接口基地址")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

配置完成后,所有通过该 Retrofit 实例发起的请求都会自动携带指定的 Access-Key。

注意:如果 Postman 中你是把 Key 放在请求参数而非请求头中,仅需把上述添加请求头的逻辑改为对应位置的参数添加即可,绝大多数接口的 API Key 校验均采用请求头传递,和 Postman 身份验证选项卡的配置逻辑一致。

内容的提问来源于stack exchange,提问作者PerfectlySilent AuA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:15:04