【问题标题】:Attribute value must be constant in retrofit Header改造标头中的属性值必须是常量
【发布时间】:2021-10-27 02:19:36
【问题描述】:

II尝试调用我用nativeLib创建的API key,但是在retrofit header中调用时无法执行,并且出现消息“Attribute value must be constant”

API接口

String RAPID_API_KEY = NativeLib.apiKey();
String RAPID_API_HOST = NativeLib.apiHost();

@Headers({RAPID_API_KEY, RAPID_API_HOST}) // Error message in this line
@GET
Call<Post>getVideoByUrl(@Url String url, @Query("url") String inputUrl);

这个问题有解决办法吗?无论答案是什么,我都非常感谢。

【问题讨论】:

    标签: java android retrofit android-native-library


    【解决方案1】:

    注解属性值必须在编译时已知,只允许内联编译时常量,如下所示:

    /* static final */ String RAPID_API_KEY = "X-Header-Name: RtaW4YWRtaYWucG..."
    /* static final */ String RAPID_API_KEY = "X-Header-Name: " + "RtaW4YWRtaYWucG..."
    /* static final */ String RAPID_API_KEY = "X-Header-Name: " + Constants.API_KEY /* API_KEY = "RtaW4YWRtaYWucG..." */
    

    但不是

    String RAPID_API_KEY = NativeLib.apiKey(); /* Here compiler can't compute NativeLib.apiKey() value */
    

    或者,您可以使用@Header@HeaderMap 在参数中动态传递标头

    @GET
    Call<Post> getVideoByUrl(@HeaderMap Map<String, String> headers,
                             @Url String url,
                             @Query("url") String inputUrl);
    ...
    final Map<String, String> headers = new HashMap<>();
    headers.put("Key Header Name", NativeLib.apiKey());
    headers.put("Host Header Name", NativeLib.apiHost());
    ...
    api.getVideoByUrl(headers, ...);
    

    如果你想add the header to all requests.,你也可以使用 OkHttp 拦截器

    【讨论】:

      【解决方案2】:

      您应该尝试在 NativeLib.apiKey(); 之前添加 "" 并在 NativeLib.apiHost(); 中添加相同的内容。请参考这里https://stackoverflow.com/a/39157786/12660050In Java why this error: 'attribute value must be constant'?

      【讨论】:

      • 我试过 String RAPID_API_KEY = "" + NativeLib.apiKey();但结果还是一样
      • 你给了 headers 值的键?像@Headers("Key Name: RAPID_API_KEY")
      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 2018-11-20
      • 2020-03-06
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多