Why I get Attribute value must be constant error?

2019-06-01 19:07发布

问题:

I'm trying to add current date to url String in HTTP @GET, but I'm getting Attribute value must be constant error. I can't figure why? I'm using retrofit 2.

public interface API {

  final Date c = new Date();
  final String date=new SimpleDateFormat("yyyy-MM-dd").format(c);

  static final String url = ("/modules/json/json/Index?costNumber=0417&firstDay="+date+"&language=fi");


  @GET(url)
  Call<Menu> getMenuName();

回答1:

As @Selvin already pointed out in the comments it's because of date not being a constant.

Using retrofit you usually make this a query parameter, so you can change getMenuName to:

@GET("/modules/json/json/Index")
Call<Menu> getMenuName(
       @Query("costNumber") String costNumber,
       @Query("firstDay") String firstDay,
       @Query("language") String language);

You can then call the method with the proper parameters:

getMenuName("0417", date, "fi");

Retrofit will know how to build the url for you. Notice that this makes it also much easier to make the same call with different costNumber and firstDay, than having a hardcoded url.



回答2:

Fred's answer is the correct solution for your case. However, for the sake of complete information, Retrofit 2 does support dynamic URLs. You can pass it as a @Url parameter to your interface method, for example:

@GET
Call<ResponseBody> getMenuName(@Url String url);

You don't need to specify the URL in the @GET annotation. Retrofit will take the value from the passed url. This gives you the option to request data from dynamic URLs, which can be useful in some cases.

You can find more info here: https://futurestud.io/tutorials/retrofit-2-how-to-use-dynamic-urls-for-requests