Spring Boot调用GET API遭遇HttpClientErrorException$BadRequest 400错误
解决Spring Boot调用GET API出现400 Bad Request的问题
问题根源
- GET请求参数传递方式错误:你把请求参数放在了
HttpEntity的body中,但GET请求不支持通过body传递参数,服务器无法识别这些参数,直接返回400错误。 - 日期格式转换不匹配:API要求参数格式为
yyyy-MM-dd HH:mm:ss,但RestTemplate默认的参数转换逻辑可能无法将LocalDateTime对象正确转为该格式的字符串。
修复方案
方案一:手动构建带参数的URL(推荐)
直接通过UriComponentsBuilder把参数拼到URL的查询字符串中,同时手动格式化日期:
HttpHeaders headers = new HttpHeaders(); LocalDate dateValue = LocalDate.now(); LocalDateTime restrictProfileDate = dateValue.atStartOfDay(); // 构建符合要求的请求URL UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(apiEndPoint) .queryParam("restrictProfileDate", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(restrictProfileDate)); HttpEntity<String> requestEntity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange( urlBuilder.toUriString(), HttpMethod.GET, requestEntity, String.class );
方案二:全局配置RestTemplate的日期转换器
如果需要多次调用这类带日期参数的API,可以给RestTemplate添加自定义转换器,统一处理日期格式:
@Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // 注册Java 8时间模块 objectMapper.registerModule(new JavaTimeModule()); // 指定日期转换格式 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); converter.setObjectMapper(objectMapper); restTemplate.getMessageConverters().add(converter); return restTemplate; }
配置完成后,调用时直接通过参数占位符传递LocalDateTime对象即可:
HttpHeaders headers = new HttpHeaders(); LocalDate dateValue = LocalDate.now(); Map<String, Object> params = new HashMap<>(); params.put("restrictProfileDate", dateValue.atStartOfDay()); ResponseEntity<String> response = restTemplate.exchange( apiEndPoint + "?restrictProfileDate={restrictProfileDate}", HttpMethod.GET, new HttpEntity<>(headers), String.class, params );
核心注意事项
- GET请求参数必须通过URL查询字符串传递,不能放在请求body中,这是HTTP协议的规范。
- 传递的日期字符串必须严格匹配API定义的
yyyy-MM-dd HH:mm:ss格式,包括日期和时间之间的空格。
内容的提问来源于stack exchange,提问作者Parth Atara
相关产品推荐
相关产品推荐

