Spring Boot中如何避免RestTemplate将查询参数中的空格替换为%20
问题原因
你当前遇到的问题是UriComponentsBuilder默认遵循RFC 3986标准对URL特殊字符做自动编码,空格会被转义为%20,而目标第三方API未做URL解码逻辑,因此会直接存储转义后的字符。Postman发送请求时不会对查询参数的空格做强制编码,因此可以正常提交。
方案1:关闭UriComponents的自动编码逻辑
在构建URI时指定不执行自动编码,直接保留参数原始内容,修改代码如下:
@Override public boolean insertNotaryDistrictDetailsAsPost(NotaryDistrictDetails notaryDistrict) { HttpHeaders basicAuthHeader = this.getWpBasicAuthenticationHeader(); HttpEntity<String> request = new HttpEntity<String>(basicAuthHeader); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(wpPortalWriteNotaryDistrictDetailsAsPostUrl) // BASIC INFO: .queryParam("title", notaryDistrict.getDistretto()) .queryParam("wpcf-distretto-notary-district", notaryDistrict.getDistretto()) .queryParam("wpcf-indirizzo-notary-district", notaryDistrict.getIndirizzo()) .queryParam("wpcf-denominazione-notary-district", notaryDistrict.getDenominazione()) .queryParam("wpcf-provincia-notary-district", notaryDistrict.getProvincia()) .queryParam("wpcf-regione-notary-district", notaryDistrict.getRegione()) .queryParam("wpcf-cap-notary-district", notaryDistrict.getCap()) .queryParam("wpcf-telefono-notary-district", notaryDistrict.getTelefono()) .queryParam("wpcf-fax-notary-district", notaryDistrict.getFax()) .queryParam("wpcf-email-notary-district", notaryDistrict.getEmail()) .queryParam("wpcf-pec-notary-district", notaryDistrict.getPec()) .queryParam("wpcf-web-url-notary-district", notaryDistrict.getWebUrl()); // 关键修改:指定encoded=true,不对已拼接的参数做二次编码 String finalUrl = builder.build(true).toUriString(); // 若仍有%20,可手动替换:finalUrl = finalUrl.replaceAll("%20", " "); ResponseEntity<String> response = restTemplate.exchange(finalUrl, HttpMethod.POST, request, String.class); System.out.println("RESPONSE STATUS: " + response.getStatusCodeValue()); System.out.println(response.getBody()); return true; }
方案2:全局配置RestTemplate关闭URL编码
如果需要多个请求都遵循该规则,可自定义RestTemplate的URI构建工厂,关闭默认编码逻辑:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); DefaultUriBuilderFactory uriFactory = new DefaultUriBuilderFactory(); // 关闭自动编码 uriFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); restTemplate.setUriTemplateHandler(uriFactory); return restTemplate; } }
配置后直接使用URI模板传参即可,无需额外处理空格。
方案3:手动拼接URL参数
如果参数数量少,可直接手动拼接查询参数,空格直接保留,完全跳过自动编码逻辑:
String finalUrl = wpPortalWriteNotaryDistrictDetailsAsPostUrl + "?title=" + notaryDistrict.getDistretto() + "&wpcf-distretto-notary-district=" + notaryDistrict.getDistretto(); // 剩余参数依次拼接即可
注意:如果参数中存在&、=等特殊字符,需要你手动做处理,避免URL结构被破坏。
内容的提问来源于stack exchange,提问作者AndreaNobili
相关产品推荐
相关产品推荐

