feign发送Get请求

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

@FeignClient("microservice-provider-user")

publicinterfaceUserFeignClient {

@RequestMapping(value ="/user", method = RequestMethod.GET)

publicUser get0(User user);

}

那么在调试的时候你会一脸懵逼,因为报了如下错误:

feign.FeignException: status405reading 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,于是就开始逐行调试,直到我发现了这个:

privatesynchronizedOutputStream getOutputStream0()throwsIOException {

try{

if(!this.doOutput) {

thrownewProtocolException("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,我们用了如下配置:

?

1

 

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)

publicUser get0(User user);

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

@RequestMapping(value ="/user", method = RequestMethod.GET)

publicUser get0(@RequestBodyUser user);

以上就是Feign发送Get请求时怎么用对象传递参数的全文介绍,希望对您学习和使用程序编程有所帮助.

得到请求 发送ajax,得到相应的结果,然后填充到实体

猜你喜欢

转载自blog.csdn.net/qq_33243164/article/details/89500046