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

Spring Boot 3.2.0-M3中411 Length Required错误的解决方法

解决Spring Boot 3.2.0-M3中POST请求的411 Length Required错误

你遇到的411错误是因为MTN的API服务器要求POST请求必须包含有效的Content-Length头,当前代码的处理方式导致该头未被正确传递。以下是具体解决方案:

核心原因

当设置MediaType.APPLICATION_FORM_URLENCODED但未提供请求体时,Spring RestClient的自动处理逻辑可能会忽略甚至移除你手动添加的Content-Length: 0头,导致服务器收到的请求不符合校验要求。

解决方案

方案1:发送空的表单请求体

为APPLICATION_FORM_URLENCODED类型的请求提供空表单数据,让Spring自动生成正确的Content-Length头:

public AccessToken accessToken() {
    var subscriberKey = "exxxx";
    var authorization = "Basic " + Base64.getEncoder().encodeToString(
            String.format("%s:%s", "xxxxxxx", "yyyyyy").getBytes()
    );
    return RestClient.create().post()
            .uri("https://sandbox.momodeveloper.mtn.com/collection/token/")
            .headers(h -> {
                h.add("Authorization", authorization);
                h.add("Ocp-Apim-Subscription-Key", subscriberKey);
            })
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(MultiValueMap.empty()) // 传递空表单作为请求体
            .retrieve()
            .body(AccessToken.class);
}

方案2:使用HttpEntity明确控制请求头和体

通过HttpEntity封装空请求体和自定义头,确保Content-Length被正确保留:

public AccessToken accessToken() {
    var subscriberKey = "exxxx";
    var authorization = "Basic " + Base64.getEncoder().encodeToString(
            String.format("%s:%s", "xxxxxxx", "yyyyyy").getBytes()
    );
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", authorization);
    headers.set("Ocp-Apim-Subscription-Key", subscriberKey);
    headers.set("Content-Length", "0");
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<Void> requestEntity = new HttpEntity<>(null, headers);

    return RestClient.create()
            .post()
            .uri("https://sandbox.momodeveloper.mtn.com/collection/token/")
            .body(requestEntity)
            .retrieve()
            .body(AccessToken.class);
}

方案3:确认API是否支持GET请求(可选)

部分Token接口允许用GET请求获取令牌,如果MTN的沙箱API支持这种方式,可将请求方式改为get(),规避POST请求的Content-Length校验问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:50:23