本文共 2119 字,大约阅读时间需要 7 分钟。
在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();} 使用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); 测试代码如下:
@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);} 使用@RequestBody注解来接收JSON格式的请求体。示例代码如下:
@PostMapping("/post/body")public String test03(@RequestBody User user) { return user.toString();} 测试代码如下:
@Testpublic void test03() { User user = new User(); user.setAge(13); user.setName("Wade"); String response = client.invokeTest03(user); System.out.println(response);} 同时接收URL参数和请求体参数。示例代码如下:
@PostMapping("/post/bodyAndUrl")public String test04(@RequestParam Map map, @RequestBody User user) { return map.toString();} 使用@Body注解和@Headers注解来定义请求体和请求头。示例代码如下:
@RequestLine("POST /feign/provider/post/bodyAndUrl")@Body("{body}")@Headers({"content-type: application/json"})String invokeTest04(@QueryMap Map map, @Param("body") User user); 测试代码如下:
@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/