使用Feign,如何在Get和Post请求中传入对象?

Get请求中,包含多个参数

在Get接口中,使用包含多个属性的对象来来接收多个参数

@GetMapping("/test")
public void test(User user) {
    //省略……
}

@Data
public class User implements Serializable {
    private Integer id;
    private String username;
}

此时,请求的URL需要为

/test?id=1&username=qqcr

使用FeignClient来请求上述Get接口

  • 方法一
    在feign client中,使用User对象作为参数,但是需要在参数前面加上@SpringQueryMap注解,来让框架将User对象解析成方法二的样子
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @GetMapping("/test")
  public User get0(@SpringQueryMap User user);
}
  • 方法二
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get1(@RequestParam("id") Long id, @RequestParam("username") String username);
}
  • 方法三
    这种方式不推荐,因为不知道map中需要什么属性,可读性不高。
    而且如果参数为空的时候会有一些问题,例如 map.put(“username”, null); 会导致microservice-provider-user 服务接收到的username是"" ,而不是null。
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get2(@RequestParam Map<String, Object> map);
}

但是在调用的时候,需要使用如下代码的方式来构建map对象

public User get(String username, String password) {
  HashMap<String, Object> map = Maps.newHashMap();
  map.put("id", "1");
  map.put("username", "张三");
  return this.userFeignClient.get2(map);
}
  • 错误的调用示范
    如果直接使用类似于方法一种的方法,不加@SpringQueryParam,则方法会被自动转换为POST请求,然后报错。
    调用代码如下
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/test", method = RequestMethod.GET)
  public User get0(User user);
}

报错如下

feign.FeignException: status 405 reading UserFeignClient#get0(User); content:
{"timestamp":1482676142940,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get"}

Post请求包含多个参数

定义接口,使用对象接收参数

User对象前需要加上@RequestBody注解。

@RestController
public class UserController {
  @PostMapping("/test2")
  public User post(@RequestBody User user) {
    ...
  }
}

使用Feign进行调用,传入对象作为参数

User对象前需要加上@RequestBody注解。

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/test2", method = RequestMethod.POST)
  public User post(@RequestBody User user);
}

参考

如何使用Feign构造多参数的请求

GET请求,接收多个对象参数

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值