Java编写的ECS Fargate任务调用API Gateway时POST请求体为空
问题修复:ECS Fargate向API Gateway发送POST请求体为空
问题原因
你当前的代码仅通过contentStreamProvider提供了请求体的输入流,但未设置Content-Length请求头,也未让SDK自动处理内容长度。API Gateway接收请求时,因无法确定请求体长度,无法正确读取完整内容,最终导致请求体为空,触发参数非空验证错误。
解决方案
提供两种可靠修复方式:
方式一:手动设置Content-Length头
先计算请求体字节长度,添加到请求头中,保留contentStreamProvider:
byte[] requestBodyBytes = requestBody.getBytes(StandardCharsets.UTF_8); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .uri(uri) .method(SdkHttpMethod.POST) .putHeader("Content-Type", "application/json") .putHeader("Content-Length", String.valueOf(requestBodyBytes.length)) .contentStreamProvider(() -> new ByteArrayInputStream(requestBodyBytes)) .build();
方式二:直接使用content方法传入SdkBytes
这种方式更简洁,SDK会自动计算并设置Content-Length头:
SdkBytes sdkBytes = SdkBytes.fromString(requestBody, StandardCharsets.UTF_8); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .uri(uri) .method(SdkHttpMethod.POST) .putHeader("Content-Type", "application/json") .content(sdkBytes) .build();
验证建议
修复后重新部署Fargate任务,查看API Gateway日志,确认Method request body before transformations字段显示正确的JSON请求体,后端参数验证错误即可消除。
内容的提问来源于stack exchange,提问作者10110
相关产品推荐
相关产品推荐

