参见楼下的解释,其实是微信会检查Content-Length参数,但Spring Framework 6.1以后请求不再设置该参数(可以参加SimpleClientHttpRequestFactory中的setBufferRequestBody说明);另外可以debug看一下请求报文中的{Transfer-Encoding: chunked} 自己在http header中自己设置Content-Length就行了 String body = JSONObject.toJSONString(params); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setContentLength(body.getBytes(StandardCharsets.UTF_8).length); HttpEntity entity = new HttpEntity<>(body, headers); ResponseEntity bResp = restTemplate.postForEntity(url, entity, String.class);
小程序手机号解析接口一直报 412 Precondition Failed: [no body]?public String getPhoneNumber(String phoneCode) { JSONObject params = new JSONObject(); params.put("code", phoneCode); String url = MessageFormat.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={0}", getAccessToken()); JSONObject reObj = restTemplate.postForObject(url, params, JSONObject.class); if (reObj != null && reObj.containsKey("errcode")) { log.info(reObj.toJSONString()); if (reObj.getInteger("errcode") == 0) { Code2PhoneNumberResponse code2PhoneNumberResponse = JSONObject.parseObject(reObj.toJSONString(), Code2PhoneNumberResponse.class); return code2PhoneNumberResponse.getPhoneInfo().getPurePhoneNumber(); } } return null; }
2024-09-09