为什么我得到 Attribute value must be constant 错误? [英] Why I get Attribute value must be constant error?

查看:2311
本文介绍了为什么我得到 Attribute value must be constant 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将当前日期添加到 HTTP @GET 中的 url 字符串,但我收到 Attribute value must be constant 错误.我想不通为什么?我正在使用改造 2.

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

推荐答案

正如@Selvin 在评论中已经指出的那样,这是因为 date 不是一个常量.

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

使用改造您通常将其设为查询参数,因此您可以将 getMenuName 更改为:

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 将知道如何为您构建 url.请注意,这使得使用不同的 costNumberfirstDay 进行相同的调用比使用硬编码的 url 更容易.

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.

这篇关于为什么我得到 Attribute value must be constant 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆