Spring Web的RestClient是否支持传递@RequestParam参数?
Spring RestClient 如何传递@RequestParam参数?
RestClient完全支持传递@RequestParam对应的查询参数,以下是两种常用的实现方式,结合你的代码给出修改示例:
方式一:在URI中使用占位符传递参数
通过在URI字符串中定义占位符,然后传入参数值,RestClient会自动处理参数编码和拼接:
import org.springframework.web.client.RestClient; import org.springframework.http.MediaType; import org.springframework.core.ParameterizedTypeReference; RestClient restClient = RestClient.create("http://localhost:8095"); // 替换为实际的邮箱值 String ownerEmail = "user@example.com"; List<VideoDto> result = restClient.get() .uri("/db/video/getall?ownerEmail={ownerEmail}", ownerEmail) .accept(MediaType.APPLICATION_JSON) .retrieve() .body(new ParameterizedTypeReference<List<VideoDto>>() {});
方式二:使用UriBuilder构建带查询参数的URI
如果需要传递多个查询参数,或者更灵活地构建请求地址,推荐使用UriBuilder的queryParam方法:
import org.springframework.web.client.RestClient; import org.springframework.http.MediaType; import org.springframework.core.ParameterizedTypeReference; RestClient restClient = RestClient.create("http://localhost:8095"); String ownerEmail = "user@example.com"; List<VideoDto> result = restClient.get() .uri(uriBuilder -> uriBuilder .path("/db/video/getall") .queryParam("ownerEmail", ownerEmail) // 若有其他参数,可继续添加 .queryParam("paramName", paramValue) .build()) .accept(MediaType.APPLICATION_JSON) .retrieve() .body(new ParameterizedTypeReference<List<VideoDto>>() {});
说明
- 上述两种方式都会自动处理URL编码,避免手动拼接字符串导致的编码错误或安全问题。
- 你当前使用的Spring Boot 3.2.1和Spring Web 6.1.2版本完全支持这些写法,无需额外依赖。
内容的提问来源于stack exchange,提问作者KnowledgePath
相关产品推荐
相关产品推荐

