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

来源:互联网 发布:阿里云 吉峰农机 编辑:程序博客网 时间:2024/06/05 08:28

在使用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,consumer="application/json")
  public User get0(@RequestBody User user);
阅读全文
0 0
原创粉丝点击