Fork me on GitHub

feignclient发送get请求,传递参数为对象

feignclient发送get请求,传递参数为对象。此时不能使用在地址栏传递参数的方式,需要将参数放到请求体中。

  • 第一步:

修改application.yml中配置feign发送请求使用apache httpclient 而不是默认的jdk UrlConnection

1
feign.httpclient.enabled= true
  • 第二步:

pom.xml中增加对apache httpclient的支持。

1
2
3
4
5
6
7
8
9
10
11
<!-- 配置feign 发送请求使用 httpclient,而不是java原生 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <!-- 使用Apache HttpClient替换Feign原生httpclient -->
        <dependency>
            <groupId>com.netflix.feign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>8.15.1</version>
        </dependency>
  • 第三步:编写接口类

在ApacheHttpClient中看到默认设置的Content-Type是ContentType.DEFAULT_TEXT,即text/plain; charset=ISO-8859-1, 此时传递对象需要配置为application/json

1
2
3
4
5
6
7
8
9
10
@FeignClient(name="feign-consumer")
public interface ServiceClient {
 
    /**@param user
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/test4",consumes="application/json")
    String getInstanceInfo4(User user);
 
}
  • 第四步:编写接收请求类
1
2
3
4
5
6
7
8
9
10
/**Feign发送Get请求时用对象传递参数
 * @param servers
 * @return
 */
@RequestMapping(value="/test4", method = RequestMethod.GET,consumes="application/json"
public String firstDemo4(@RequestBody User u) {
     
    System.out.println(u);
    return "hello3"+u;
}  

  参考链接:

    https://blog.csdn.net/cuiyaoqiang/article/details/81215483

 

上手,运行。。。报错:Caused by: java.lang.NoSuchMethodError: feign.Response.create(ILjava/lang/String;Ljava/util/Map;Lfeign/Response$Body;)Lfeign/Response;

  参考 https://ask.csdn.net/questions/773444 这个问答,得知需要修改依赖版本

1
2
3
4
5
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>10.1.0</version>
</dependency>

  完美解决

以上操作可用SpringQueryMap注解代替(前提spring cloud2.1.x及以上版本):

  spring cloud项目使用feign的时候都会发现一个问题,就是get方式无法解析对象参数。其实feign是支持对象传递的,但是得是Map形式,而且不能为空,与spring在机制上不兼容,因此无法使用。

spring cloud在2.1.x版本中提供了@SpringQueryMap注解,可以传递对象参数,框架自动解析,只可惜啊,得是2.1.0以后的版本。
1
2
3
4
5
6
@FeignClient(name="feign-consumer")
public interface ServiceClient {
 
    @RequestMapping(method = RequestMethod.GET, value = "/test4")
    String getInstanceInfo4(@SpringQueryMap User user);
}

  参考链接:

    http://www.itmuch.com/spring-cloud-sum/feign-multiple-params-2/

 
posted @   威威超酷  阅读(13003)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示