Spring Boot Feign requestParam 包含一个数组

Spring Boot Feign requestParam containing an array

我正在尝试查询 https://transport.opendata.ch/ API。在这个 API 中,可以过滤响应以避免大负载(使用 ?fields[]=...)。

例如:http://transport.opendata.ch/v1/connections?from=Lausanne&to=Zurich&fields[]=connections/from&fields[]=connections/to

我正在使用 Spring Boot and Feign,这是我的代码:

@FeignClient(value = "transport", url = "${transport.url}")
public interface TransportClient {

    @RequestMapping(method = GET, value = "/connections", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Connections getConnections(@RequestParam("from") String from, @RequestParam("to") String to, @RequestParam("fields[]") String[] fields);

    default Connections getConnections(String from, String to) {
        return getConnections(from, to, new String[] {"connections/from", "connections/to"});
    }
}

问题是生成的请求:

http://transport.opendata.ch/v1/connections?from=Lausanne&to=Zurich&fields%5B%5D=connections%2Ffrom%2Cconnections%2Fto

如您所见,url 被编码并且数组未正确绑定(使用逗号而不是 url 中的几个 fields)。

有什么办法可以实现吗?如果不能用 FeignClient (Spring),也许用 Feign 可以吗?

感谢您的帮助。

我刚刚找到了解决方案:

@FeignClient(value = "transport", url = "${transport.url}")
public interface TransportClient {

    @RequestMapping(method = GET, value = "/connections?fields[]=connections/from&fields[]=connections/to", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Connections getConnections(@RequestParam("from") String from, @RequestParam("to") String to);
}

我很幸运,因为我的字段是静态的,所以我可以将它们直接放在 URI 中,但是如何以通用方式正确处理它?

您的典型请求如下所示:

 /api?fields=1&fields=2&fields=3

 /api?fields=1,2,3

控制器方法是:

@RequestMapping(method = GET, value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
Connections getConnections(@RequestParam("fields") List<String> fields)