【问题标题】:Can API keys be added to the header using Retrofit2 android可以使用 Retrofit2 android 将 API 密钥添加到标头吗
【发布时间】:2022-01-11 07:58:28
【问题描述】:

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

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

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

code

【问题讨论】:

    标签: android api retrofit2 api-key


    【解决方案1】:

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

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

    然后在改造内部

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

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

    【讨论】:

      【解决方案2】:

      您可以发送如下标题:

      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 并传递所需的 Field 和 Headers。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 2019-05-02
        • 2021-10-24
        • 1970-01-01
        • 2020-07-09
        • 2015-10-08
        • 2016-11-20
        相关资源
        最近更新 更多