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

如何用RestTemplate发送无请求体POST请求?请求报错求助

解决RestTemplate发送无请求体POST请求报Bad Request的问题

直接给你几个可行的调整方案,按顺序尝试:

方案1:移除手动设置的Content-Length,使用Void泛型的HttpEntity

你代码里手动设置Content-Length:0会干扰RestTemplate的自动处理逻辑,改成以下代码:

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "<token>");
// 移除Content-Length的手动设置
HttpEntity<Void> entity = new HttpEntity<>(null, headers);
ResponseEntity<E> response = null;
try {
    response = restTemplate.exchange(api, HttpMethod.POST, entity, type);
} catch (Exception e) {
    // 补充异常处理逻辑
}

方案2:显式指定适配的Content-Type

如果方案1无效,尝试给请求头添加明确的无内容类型,适配部分接口对请求头的校验要求:

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "<token>");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpEntity<Void> entity = new HttpEntity<>(null, headers);
ResponseEntity<E> response = restTemplate.exchange(api, HttpMethod.POST, entity, type);

方案3:使用postForEntity简化写法

若前两种方案都不行,试试postForEntity的简化重载,直接传入仅含请求头的实体:

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "<token>");
HttpEntity<Void> entity = new HttpEntity<>(headers);
ResponseEntity<E> response = restTemplate.postForEntity(api, entity, type);

问题核心原因

Postman发送无请求体的POST时,不会主动添加多余请求头,且能正确处理Content-Length。而你原代码手动设置Content-Length,加上RestTemplate对null请求体的默认处理逻辑,导致请求头与接口预期不符,触发Bad Request。

内容的提问来源于stack exchange,提问作者Jithin M V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:41:54