【问题标题】:Replace string in Retrofit GET request in Android在 Android 的 Retrofit GET 请求中替换字符串
【发布时间】:2017-01-02 15:45:30
【问题描述】:

我正在尝试替换我的 GET 网址中的字符串。查询如下:

@GET("read/something/Books?$filter=(substringof('{filter}',Description)+or+substringof('{filter}',Code)+or+substringof('{filter}',Title)+or+substringof('{filter}',Barcode))")
    Call<ApiResponse<Book>> getFilteredBooks(@Path("filter") String filter);

所以我想用动态字符串替换 {filter}。 我收到一个错误:

java.lang.IllegalArgumentException: URL query string "$filter=(substringof('{filter}',Description)+or+substringof('{filter}',Code)+or+substringof('{filter}',Title)+or+substringof('{filter}',Barcode))" must not have replace block. For dynamic query parameters use @Query.

我找不到任何其他可以按预期工作的合适注释。

【问题讨论】:

  • 对于初学者来说,错误消息告诉你问题是什么。你需要使用@Query 而不是@Path。 filter 是查询参数而不是路径参数

标签: android rest retrofit2


【解决方案1】:

您应该使用查询参数,例如:

@GET("read/something/Books")
    Call<ApiResponse<Book>> getFilteredBooks(@Query("$filter") String filter);

这将创建像.../read/something/Books?$filter={parameter you sent} 这样的网址。

【讨论】:

  • 感谢您的回答。我知道我可以使用@Query。但是看起来非常麻烦。我需要调用getFilteredBooks("(substringof('SCRUM',Description)+or+substringof('SCRUM',Code)+or+substringof('SCRUM',Title)+or+substringof('SCRUM',Barcode))") 在很多地方多次调用它时不灵活,也许我将来想添加一些另一个过滤字段。真的没有办法简单地将url中的一个字符串替换为另一个字符串吗?
  • 好的,我知道你想做什么,但是这些长字符串请求让我很困惑。所以你可以建立你的查询参数,你可以创建一个方法buildQueryParam(String filter) { return " (substringof('+ filter + ',Description)} + ...,在所有地方设置过滤器。然后,此方法为查询参数返回正确的字符串:getFilteredBooks(buildQueryParam("SCRUM"))
猜你喜欢
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
相关资源
最近更新 更多