【问题标题】:Spring Boot Feign requestParam containing an arraySpring Boot Feign requestParam 包含一个数组
【发布时间】:2018-11-05 22:13:10
【问题描述】:

我正在尝试查询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 和 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 是可能的?

感谢您的帮助。

【问题讨论】:

    标签: arrays spring spring-boot spring-cloud-feign feign


    【解决方案1】:

    您的典型请求如下所示:

     /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)
    

    【讨论】:

    • 最终解决方案如下:@RequestMapping(method = GET, value = "/connections",produces = MediaType.APPLICATION_JSON_UTF8_VALUE) Connections getConnections(@RequestParam("from") String from, @ RequestParam("to") String to, @RequestParam("fields[]") List fields);默认连接 getConnections(String from, String to) { return getConnections(from, to, Arrays.asList("connections/from", "connections/to")); }
    【解决方案2】:

    我刚刚找到了解决方案:

    @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 中,但是如何以通用方式正确处理呢?

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 2019-09-25
      • 2019-02-11
      • 2016-05-11
      • 2017-09-22
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多