You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RestTemplate调用客户端API为何报HttpClientErrorException:400 Bad Request?

解决Spring RestTemplate调用API时的400 Bad Request错误

碰到RestTemplate调用API返回400 Bad Request?别慌,这个错误本质是你发送的请求不符合服务端的校验规则,直接被打回来了。结合你给出的Spring相关堆栈信息,我给你梳理几个最常见的排查方向和解决办法:

  • 请求参数/Body结构不匹配
    这是最常见的原因:

    • 检查请求Body的字段是否和服务端API定义完全一致,比如字段名拼写(userName vs username)、数据类型(把字符串传给数字字段)、必填字段有没有遗漏。
    • 如果发送JSON格式,确认RestTemplate配置了正确的消息转换器(比如MappingJackson2HttpMessageConverter),实体类的注解(比如@JsonProperty)是否和服务端字段对应。
      举个例子:如果服务端要求传email字段,你代码里写成了e-mail,直接就会触发400。
  • 请求头不符合服务端要求
    很多API会强制要求特定请求头,比如Content-Type必须是application/json,或者需要携带认证Token:

    • 先拿Postman/curl模拟请求,确认请求头正确后,再对应调整RestTemplate的配置。
    • 示例代码:
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer your-auth-token");
    HttpEntity<YourRequestDto> requestEntity = new HttpEntity<>(yourRequestBody, headers);
    restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, YourResponseDto.class);
    
  • 请求参数编码问题
    如果请求URL里的参数包含中文、空格或特殊字符,没正确编码也会导致400:

    • 推荐用UriComponentsBuilder构建URL,它会自动处理参数编码:
    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(apiUrl)
            .queryParam("searchKey", "测试特殊字符")
            .build(true); // true开启自动编码
    restTemplate.getForObject(uriComponents.toUriString(), YourResponseDto.class);
    
  • 获取服务端返回的具体错误信息
    默认的DefaultResponseErrorHandler只会抛出笼统的400异常,看不到服务端到底嫌你哪里错了。可以自定义错误处理器来抓取详细错误:

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
            String errorDetails = new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8);
            // 把服务端的错误信息塞进异常里,方便排查
            throw new HttpClientErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), errorDetails.getBytes(), StandardCharsets.UTF_8);
        }
    });
    

    这样抛出的异常会包含服务端返回的具体错误描述,能帮你快速定位问题。

总的来说,先通过Postman验证请求是否能正常调用,再对比RestTemplate的请求配置,重点检查参数结构、请求头、编码这几个点,必要时用自定义错误处理器获取详细错误信息,问题基本就能解决。

内容的提问来源于stack exchange,提问作者App User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:40:24