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

使用Feign Client调用无请求体POST接口时遇411 Length Required错误

解决Feign Client调用无请求体POST接口时的411 Length Required错误

问题详情

我需要调用一个不接收请求体的POST接口,使用Feign Client的代码如下:

@FeignClient(name = "Client" , url = "${URL}" , configuration = Configuration.class)
public interface FeignClient {
@PostMapping(value = "/url/abc/{id}" , consumes = {"text/html"})
@Headers("Content-Length: 0")  
void abcMethod(
            @RequestHeader Map<String, String> Headers,
            @PathVariable("id") String id
    );
}

同时在请求头Map中添加了以下参数:

{ 
    headers.put(ApplicationConstant.ACCEPT_HEADER_NAME, MediaType.APPLICATION_JSON.toString()); 
    headers.put(ApplicationConstant.AUTHORIZATION, token); 
    headers.put(ApplicationConstant.TRACE_ID , traceId); 
    headers.put("Content-Type", "text/plain; charset=us-ascii"); // 试过移除该参数
    headers.put("Content-Length" , "0"); 
} 

但始终收到411 Length Required错误,错误信息:

411 Length Required

<h2>Length Required</h2>
<hr><p>HTTP Error 411. The request must be chunked or have a content length.</p>

已尝试的方案(均未解决):

  • 在请求头中添加content-length=0
  • 添加@Body("{}")注解
  • 让控制器返回ResponseEntity<Void>(HttpStatus.NO_CONTENT)

可行解决方案

1. 显式指定空请求体

调整Feign接口方法,添加@RequestBody(required = false)的空参数,同时修正consumes属性(若接口无特定Content-Type要求,可改为通用类型):

@FeignClient(name = "Client" , url = "${URL}" , configuration = Configuration.class)
public interface FeignClient {
    @PostMapping(value = "/url/abc/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
    void abcMethod(
            @RequestHeader Map<String, String> headers,
            @PathVariable("id") String id,
            @RequestBody(required = false) Void emptyBody
    );
}

调用时传入null作为空请求体,Feign会自动处理Content-Length为0的逻辑。

2. 自定义Feign拦截器统一设置请求头

创建拦截器,针对无请求体的POST请求强制设置Content-Length,避免手动设置的冲突:

@Component
public class FeignEmptyBodyInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        if (HttpMethod.POST.name().equals(template.method()) && template.body() == null) {
            template.header("Content-Length", "0");
            template.header("Content-Type", MediaType.TEXT_PLAIN_VALUE);
        }
    }
}

将该拦截器注册到FeignClient的configuration中,或作为全局配置生效。

3. 移除重复的Content-Length设置

当前代码同时通过@Headers("Content-Length: 0")和请求头Map添加该参数,可能导致头信息冲突。建议只保留一种设置方式,优先使用拦截器或方法参数的方式。

4. 检查Feign配置的编码器/拦截器

确认Configuration.class中是否有自定义编码器或拦截器,部分组件在处理空请求体时会自动清除Content-Length头,需要调整其行为逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:22:56