博客
关于我
03 Feign发送Post请求
阅读量:226 次
发布时间:2019-03-01

本文共 2119 字,大约阅读时间需要 7 分钟。

Feign框架处理不同类型请求参数

1 URL传递参数

1.1 服务提供者

在Spring Boot应用中,可以通过@RequestParam注解来接收URL传递的参数。示例代码如下:

@PostMapping("/post")public String test01(@RequestParam String name) {    return name;}

同样,可以接收Map类型的参数:

@PostMapping("/post/map")public String test02(@RequestParam Map
map) { return map.toString();}

1.2 客户端

使用Feign客户端,可以通过@RequestLine注解来定义请求URL,并使用@Param注解来接收URL参数。示例代码如下:

@RequestLine("POST /feign/provider/post?name={name}")String invokeTest01(@Param(value = "name") String name);

同样,可以接收Map类型的参数:

@RequestLine("POST /feign/provider/post/map")String invokeTest02(@QueryMap Map
map);

1.3 测试

测试代码如下:

@Testpublic void test01() {    String response = client.invokeTest01("wade");    System.out.println(response);}
@Testpublic void test02() {    Map
map = new HashMap<>(); map.put("name", "wade"); map.put("age", 28); String response = client.invokeTest02(map); System.out.println(response);}

2 Body参数

2.1 演示

使用@RequestBody注解来接收JSON格式的请求体。示例代码如下:

@PostMapping("/post/body")public String test03(@RequestBody User user) {    return user.toString();}

2.2 API讲解

  • Body注解:用于定义请求体的结构,支持JSON格式数据。需要设置Content-Type请求头参数。
  • Headers注解:用于定义请求头,支持自定义设置。

测试代码如下:

@Testpublic void test03() {    User user = new User();    user.setAge(13);    user.setName("Wade");    String response = client.invokeTest03(user);    System.out.println(response);}

3 Body和URL参数结合使用

3.1 服务提供者

同时接收URL参数和请求体参数。示例代码如下:

@PostMapping("/post/bodyAndUrl")public String test04(@RequestParam Map
map, @RequestBody User user) { return map.toString();}

3.2 客户端

使用@Body注解和@Headers注解来定义请求体和请求头。示例代码如下:

@RequestLine("POST /feign/provider/post/bodyAndUrl")@Body("{body}")@Headers({"content-type: application/json"})String invokeTest04(@QueryMap Map
map, @Param("body") User user);

3.3 测试

测试代码如下:

@Testpublic void test04() {    User user = new User();    user.setAge(13);    user.setName("Wade");    Map
map = new HashMap<>(); map.put("name", "kobe"); map.put("age", 28); String response = client.invokeTest04(map, user); System.out.println(response);}

通过以上方法,可以在Feign框架中高效地处理不同类型的请求参数。

转载地址:http://oprv.baihongyu.com/

你可能感兴趣的文章
QGIS怎样设置简体中文以及新建可编辑的多边形的图层
查看>>
PowerBuilder 使用自定义事件触发键盘Enter事件
查看>>
PowerCreatorCMS UploadResourcePic 任意文件上传漏洞复现
查看>>
PowerDesigner 使用的一些技巧(转)
查看>>
QGIS在Windows上下载安装与建立空间数据库连接
查看>>
PowerDesigner165安装婆姐汉花教程
查看>>
PowerDesigner使用教程:设置注释、默认值属性
查看>>
PowerDesigner使用教程:不显示背景网格
查看>>
PowerDesigner使用教程:创建数据模型以及导出
查看>>
PowerDesigner使用教程:右侧工具栏显示/隐藏
查看>>
PowerDesigner使用教程:导出sql文件以及解决中文乱码问题
查看>>
PowerDesigner使用教程:时间字段设置
查看>>
PowerDesigner使用教程:给字段添加唯一约束
查看>>
QGIS中怎样设置图层样式并导出地图样式
查看>>
PowerDesigner使用笔记
查看>>
QGIS中怎样实现数据坐标系转换
查看>>
PowerDesigner学习--基本步骤
查看>>
PowerDesigner导出Report通用报表
查看>>
PowerDesigner教程系列(二)概念数据模型
查看>>
Powerdesigner显示表的comment和列的comment的方法
查看>>