如何修复Spring WebClient/RestTemplate通过queryParams传SQL的解析错误?
问题原因
你使用WebClient.uri(url, queryParams)的方式有误,这个方法是用来替换URL中的模板变量(比如/api/{id}里的{id}),并非用于添加查询参数。你的SQL查询参数要么没被正确附加到URL的查询字符串中,要么因特殊字符(空格、=等)未被正确URL编码,导致后端解析失败。而硬编码URL时,浏览器或工具会自动完成正确的URL编码,所以能正常运行。
解决方案
以下两种方式可正确构建带查询参数的请求URI,确保SQL参数被正确编码和传递:
方式一:使用UriComponentsBuilder构建URI
String url = "http://localhost:8080/query"; String sqlQuery = "select count(*) from TableA where abc = true"; // 自动处理URL编码,构建带查询参数的URI URI uri = UriComponentsBuilder.fromHttpUrl(url) .queryParam("query", sqlQuery) .build() .toUri(); WebClient webClient = WebClient.builder().build(); String result = webClient.get() .uri(uri) .retrieve() .bodyToMono(String.class) .block();
方式二:使用WebClient的URI构建器lambda
String url = "http://localhost:8080/query"; String sqlQuery = "select count(*) from TableA where abc = true"; WebClient webClient = WebClient.builder().build(); String result = webClient.get() .uri(uriBuilder -> uriBuilder.path(url) .queryParam("query", sqlQuery) .build()) .retrieve() .bodyToMono(String.class) .block();
若需传递多个查询参数,只需在UriComponentsBuilder或uriBuilder后追加多个queryParam即可。
内容的提问来源于stack exchange,提问作者Shruti Sose
相关产品推荐
相关产品推荐

