Spring Cloud中,如何使用Feign构造多参数的GET请求

2 篇文章 0 订阅
1 篇文章 0 订阅

GET请求多参数的URL

假设我们请求的URL包含多个参数,例如http://producer/hello2?name=张三&age=12

我们知道Spring Cloud为Feign添加了Spring MVC的注解支持,那么我们不妨按照Spring MVC的写法尝试一下:

@RequestMapping(value = "hello2", method = RequestMethod.GET)
public String hello2(User user) {
    return demoService.hello2(user);
}

然而我们测试时会发现该写法不正确,我们将会收到类似以下的异常:

feign.FeignException: status 405 reading DemoService#hello2(User); content:
{"timestamp":"2018-09-28T12:23:05.734+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/hello2"}

由异常可知,尽管指定了GET方法,Feign依然会发送POST请求。

正确写法如下:

(1)方法一

@RequestMapping(value = "hello2", method = RequestMethod.GET)
public String hello2(@RequestParam("name") String name, @RequestParam("age") String age) {
    return demoService.hello2(name, age);
}

这是最为直观的方式,URL有几个参数,Feign接口中的方法就有几个参数。使用@RequestParam注解指定请求的参数是什么。

(2)方法二

@RequestMapping(value = "hello2", method = RequestMethod.GET)
public String hello2(@RequestParam Map<String, Object> map) {
    return demoService.hello2(map);
}

多参数的URL也可以使用Map去构建。当目标URL参数非常多的时候,可使用这种方式简化Feign接口的编写。

版本注意:
  1. Finchley.SR1版本以前Feign的Maven是
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
  1. Finchley.SR1版本现在的Feign的Maven是
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值