boxmoe_header_banner_img

欢迎来到YaeMiko小站

加载中

文章导读

SpringBoot3与微信API对接出现413:NOBODY错误


avatar
Samele 2026-02-21 6

笔者最近在与微信公众号API对接中使用临时文件上传接口

出现412 Precondition Failed on POST request for “xxxxxx” no body错误

经过AI,CSDN,GITHUB等多方查证,springframework6+的一些版本在resttemplate发出请求时,

为了节约内存不再携带content-length字段。而微信描述的媒体字段“media”字段里:


请求体 Request Payload:

参数名 类型 必填 说明
media formdata form-data 中媒体文件标识,有filename、filelength、content-type等信息

强调了需要携带filename、filelength、content-type等信息


而自己手动计算请求体的content-length是较为复杂的工程,

CHATGPT建议使用RestTemplate+HTTPCLIENT5或者WEBFLUX的WEBCLIENT方案。

经过测试均被微信API拒绝,且报同样错误。

故笔者选择回退到springboot2.7.x版本,暂时回避该问题。等待官方解决方案

 

 

// 构造 multipart body
FileSystemResource fileResource = new FileSystemResource(file);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("media", fileResource);

// headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);

// 构造 URL
String url = UriComponentsBuilder.fromUriString("https://api.weixin.qq.com/cgi-bin/media/upload")
        .queryParam("access_token", tokenSchedule.getACCESS_TOKEN())
        .queryParam("type", type.getVal())
        .build()
        .toUriString();

ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

以上方案在springboot2.7,18上有效

 

 



评论(已关闭)

评论已关闭