可以使用 Retrofit2 android 将 API 键添加到 header

Can API keys be added to the header using Retrofit2 android

无法获得使用 API 密钥的 API 请求。已经使用不使用 API 密钥的不同 API 对其进行了测试,该密钥有效。让我觉得我没有正确添加 API 密钥。

使用身份验证选项卡在 postman 上对其进行了测试,效果很好。

如何使用 retrofit2 发送密钥 Access-Key 和值 9xxxxxxxxxxxxx3?

code

当你调用R.string.api_key时,你不会得到字符串值,你只会得到它的id,它被表示为一个数字。要获取值,您需要有上下文并调用 context.getString(R.string.api_key)。在我们的例子中,最好从 string.xml 中取出并放在 class 中。 例如

object Constants {
    const val BASE_URL = "http://test.com/"
}

然后里面改造

 return Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)

但是如果您想从 string.xml 中获取值,您需要更改示例中的 getInstance() 方法添加 Context.

您可以像这样发送 Headers:

public interface APIService {

//Login
@FormUrlEncoded
@POST("loginAction")
Call<LoginModel> loginMI(
        @Field("username") String username,
        @Field("pwd") String pwd,
        @Header("api_key") String api_key,
        @Header("secret_key") String secret_key
);

}

调用上面的 API 并传递所需的字段和 Headers。