Feign发送Get请求时,采用POJO对象传递参数的最终解决方案

转载自:https://blog.csdn.net/f641385712/article/details/82431502

叙述

spring cloud技术栈里面,Feign 可以使得我们的rest调用和调用本地方法一样方便。但是它真的有非常多的坑,苦不堪言啊。本文将描述我们最为常遇到的坑:

异常

Feign发送 Get 请求时,采用POJO传递参数,报异常

Request method ‘POST’ not supported

@FeignClient("microservice-provider-user")
public interface UserFeignClient {

  @RequestMapping(value = "/user", method = RequestMethod.GET)
  public PageBean<User> get(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":"/user"}

于是就开始逐行调试,知道我从feign的源码中发现了这个:

private synchronized OutputStream getOutputStream0() throws IOException {
  try {
      if(!this.doOutput) {
            throw new ProtocolException("cannot write to a URLConnection if doOutput=false - call setDoOutput(true)");
 } else {
      if(this.method.equals("GET")) {
           this.method = "POST";
 }

这段代码是在  HttpURLConnection  中发现的,jdk原生的http连接请求工具类,原来是因为Feign默认使用的连接工具实现类,所以里面发现只要你有body体对象,就会强制的把get请求转换成POST请求。

终上所述,这也不能怪feign,是HttpURLConnection 的问题。所以接下来我准备换一个 HttpClient 试试,因此本利我采用apache的HttpClient。但是一定,一定需要加入如下几个步骤:

开启熔断,替换 HttpURLConnection 为 HttpClient

# 开启断路器功能, feign默认该功能关闭
feign:
  # 启用熔断器
  hystrix:
    enabled: true
  # httpclient 替换 HttpURLConnection
  httpclient:
    enabled: true

在依赖中引入apache的httpclient

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5.3</version>
</dependency>

启用feign-httpclient

<dependency>
    <groupId>com.netflix.feign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>8.15.0</version>
</dependency>

修改feign

@GetMapping(value = "/queryAllEquipments", consumes = MediaType.APPLICATION_JSON_VALUE)

PageBean<PageQueryVO> queryAllEquipments(
    @RequestHeader(value = "Authorization") String token, 
    @RequestBody QueryAllEquipmentsVO vo
);

注意这里的 consumes = MediaType.APPLICATION_JSON_VALUE

这个是设置请求数据格式为 application/json,应为feign默认格式为 text/html。如果不写,则请求失败被熔断返回null

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值