在Retrofit POST请求中为何出现“Attribute value must be constant”错误?
解决Retrofit 2中“Attribute value must be constant”错误
嘿,我来帮你搞定这个问题!你遇到的这个错误,核心原因是Retrofit注解里的URL必须是编译时常量,而你现在的写法是把运行时才能拿到的token(通过Prefs.getSmartPassAccessToken()获取)直接拼到了static final字符串里,这不符合Java注解的要求——注解参数得是编译阶段就能确定的值,不能依赖运行时的方法调用结果。
下面给你两种可行的解决方案:
方案1:使用@Url注解传递完整动态URL
这种方法适合URL整体需要动态拼接的场景,直接把拼接好的URL作为方法参数传入:
public interface API { @FormUrlEncoded @POST // 这里不再写固定URL void smartpassnonpersistentlogout( @Url String fullUrl, // 动态URL参数 @Header("Content-Type") String content_type, @Field("client_id") String client_id, Callback<SmartPassResponse> callback ); }
调用接口的时候再拼接URL:
// 运行时拼接完整URL String fullUrl = "/secure/frrest/oauth2/token/" + Prefs.getSmartPassAccessToken(App.getContext()) + "?_action=revokeTokens"; // 调用接口 api.smartpassnonpersistentlogout(fullUrl, "application/x-www-form-urlencoded", yourClientId, callback);
方案2:使用@Path注解替换动态片段
如果你的URL结构固定,只有token部分是动态的,用@Path会更规范:
public interface API { @FormUrlEncoded // 用{token}占位符标记动态部分 @POST("/secure/frrest/oauth2/token/{token}?_action=revokeTokens") void smartpassnonpersistentlogout( @Path("token") String accessToken, // 传入动态token @Header("Content-Type") String content_type, @Field("client_id") String client_id, Callback<SmartPassResponse> callback ); }
调用时直接传入token即可:
String accessToken = Prefs.getSmartPassAccessToken(App.getContext()); api.smartpassnonpersistentlogout(accessToken, "application/x-www-form-urlencoded", yourClientId, callback);
两种方案都能解决你的问题,推荐用方案2,因为它更符合Retrofit的设计规范,URL结构也更清晰~
内容的提问来源于stack exchange,提问作者Ricky
相关产品推荐
相关产品推荐

