属性值在retrofit Header中必须是常量



我试图调用我用nativeLib创建的API键,但是当它在改装头中被调用时,它无法执行,并且有一条消息">属性值必须是常量">

APIInterface

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);

这个问题有解决办法吗?不管你的答案是什么,我都很感激。

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

/* 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在参数中动态传递header

@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, ...);

你也可以使用OkHttp拦截器,如果你想添加头到所有的请求。

您应该尝试添加">NativeLib.apiKey();之前,NativeLib.apiHost();也是一样。请参考这里https://stackoverflow.com/a/39157786/12660050和在Java中为什么这个错误:'属性值必须是常量'?

最新更新