首页 > 解决方案 > 请问我将如何使用 Retrofit 参数化这个端点?

问题描述

假设我想查询一个 API,该 API 具有用于搜索包含某些文本的字段的服务器方法,如下所示:

http://server:2001/tms/xdata/Customer?$filter=contains(Name, 'Walker') 

在使用 Kotlin 的 Android Studio 中,我会制作一个类似这样的界面:

    @GET("/tms/xdata/Customer")
    suspend fun fetchAllProductsContaining(@Query("name") searchTerm: String): CustomersResponse

如果我传递一个字符'e'作为searchTerm会给我:

http://server:2001/tms/xdata/Customer?name=e

但是我需要它看起来像这样:

http://server:2001/tms/xdata/Customer?%24filter=contains(lower(name)%2C'e')

因为我希望它不区分大小写,所以还要注意要搜索的文本必须有单引号。

我非常感谢你们可能得到的任何帮助。服务器是使用TMS XData用 Delphi 编写的

标签: androidkotlinretrofit

解决方案


答案是使用 QueryMap。以这种方式调用函数:

    suspend fun searchProductsRetrofit(searchTerm: String): List<Product> {
        val options: MutableMap<String, String> = HashMap()
        options["\$filter"] = "contains(lower(Name),'$searchTerm')"
        return retrofit().getProducts(options).value
    }

在您的 API 接口中将其配置为使用传入的数据,如下所示:

    @GET("/pmi/civic_amenity/CaProduct")
    suspend fun getProducts(@QueryMap options: Map<String, String>): ProductsResponse


推荐阅读