Feign发送Get请求时怎么用对象传递参数

在使用Feign来调用Get请求接口时,如果方法的参数是一个对象,例如:

@FeignClient ( "microservice-provider-user" )
public  interface  UserFeignClient {
   @RequestMapping (value =  "/user" , 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" : "/user" }


明明定义的Get请求,怎么被转换成了Post,当然你可以参照简书上的这篇文章http://www.jianshu.com/p/7ce46c0ebe9d

调整不用对象传递,一切OK,没毛病,可仔细想想,你想写一堆长长的参数吗?用一个不知道里边有什么鬼的Map吗?或者转换为post?这似乎与REST风格不太搭,会浪费url资源,我们还需要在url定义上来区分Get或者Post。

我很好奇,我定义的Get请求怎么就被转成了Post,于是就开始逐行调试,直到我发现了这个:

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默认使用的连接工具实现类,但我记得我们的工程用的是apach的httpclient替换掉了原生的UrlConnection,我们用了如下配置:

 
feign:
   httpclient:
     enabled:  true


同时在依赖中引入apache的httpclient

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

 

我在参照了这篇博客http://blog.csdn.net/neosmith/article/details/52449921后发现我们少配置了一个依赖:

<!-- 使用Apache HttpClient替换Feign原生httpclient --> 
<dependency>
   <groupId>com.netflix.feign</groupId>
   <artifactId>feign-httpclient</artifactId>
   <version>${feign-httpclient}</version>
</dependency>


那我加上这个依赖后,请求通了,但是接口接收到对象里边属性值是NULL;再看下边的定义是不是少点什么

@RequestMapping (value =  "/user" , method = RequestMethod.GET)
   public  User get0(User user);


对,少了一个注解:@RequestBody,既然使用对象传递参数,那传入的参数会默认放在RequesBody中,所以在接收的地方需要使用@RequestBody来解析,最终就是如下定义:

@RequestMapping (value =  "/user" , method = RequestMethod.GET)
   public  User get0( @RequestBody  User user);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值