【问题标题】:Attribute must be constant in Retrofit @HeaderRetrofit @Header 中的属性必须是常量
【发布时间】:2020-03-06 10:03:16
【问题描述】:

我想在改造 api 中将标头传递给每个 POST 请求。因为我听到了很多方法,所以我不能复制/粘贴每个方法的标题信息。

public interface ApiInterface {
    String[] header = {"Accept:application/json",
                       "apiKey:12345",
                       "Content-Type:application/json"};

    @Headers(header)
    @POST("signup?")
    Call<SignupResponse> createUser(@Body SignupData signupData);

    @Headers(header)
    @POST("another")
    ....
}

@HEADER 中的标头变量会产生此错误:

属性必须是常量

我该如何解决这个问题?

【问题讨论】:

  • 去掉AcceptContent-Type部分有什么问题吗?只需尝试@Header(),它需要String 类型而不是String[] 使用(“apiKey:12345”)。还有,为什么不试试 Retrofit 的 HttpInterceptor
  • SOLUTION 是@Shashanth 推荐的链接。我应该使用 HttpClient 拦截器来添加标头来改造 obj。

标签: java android header retrofit2


【解决方案1】:

试试这个

@Headers({"Accept:application/json",
            "apiKey:12345",
            "Content-Type:application/json"})
@POST("signup?")
    Call<SignupResponse> createUser(@Body SignupData signupData);

【讨论】:

  • 实际上我想避免在@Headers() 中为每种方法写3行。有可能吗?
  • 别无选择。
【解决方案2】:

用途:

@Headers({"Accept:application/json",
         "apiKey:12345",
         "Content-Type:application/json"})
@POST("another")

请参阅the Retrofit documentation 的“标题操作”部分。

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2021-10-27
    • 2013-02-09
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多