javaandroidretrofitandroid-native-library

Attribute value must be constant in retrofit Header


I I tried to call the API key that I created with nativeLib, but when it is called in the retrofit header it can't be executed and there is a message "Attribute value must be constant"

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

is there a solution for this problem? I really appreciate whatever the answer is.


Solution

  • Annotation attribute value must be known at compile-time, only inlined compile-time constants are allowed, like this:

    /* 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..." */
    

    but not

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

    Alternatively, you can pass header in parameter dynamically using @Header or @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, ...);
    

    also you can use an OkHttp interceptor if you want to add the header to all requests.