// 使用Map构建请求体,让RestClient自动序列化为JSON
java.util.Map<String, String> requestBody = new java.util.HashMap<>();
requestBody.put("code", phoneCode);
System.out.println("请求体对象: " + requestBody);
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
System.out.println("请求URL: " + url);
String raw = null;
try {
// 使用RestClient,传入Map对象让其自动序列化为JSON
raw = restClient.post()
.uri(url)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(requestBody) // 传入Map对象,RestClient会自动序列化为JSON
.retrieve()
.onStatus(status -> status.value() == 412, (request, response) -> {
System.err.println("微信API返回 412 Precondition Failed");
System.err.println("响应状态: " + response.getStatusCode());
System.err.println("响应头: " + response.getHeaders());
// 尝试读取响应体
try {
byte[] bodyBytes = response.getBody().readAllBytes();
String bodyStr = new String(bodyBytes, StandardCharsets.UTF_8);
System.err.println("响应体: " + bodyStr);
} catch (Exception ex) {
System.err.println("无法读取响应体: " + ex.getMessage());
}
throw new ApiException(HttpStatus.BAD_GATEWAY, "WECHAT_ERROR",
"微信API返回412错误。\n\n" +
"可能原因:\n" +
"1. phoneCode已过期(有效期5分钟)或已被使用\n" +
"2. 服务器IP未加入微信公众平台IP白名单\n" +
"3. 请求体格式不符合微信要求\n" +
"4. access_token无效或过期\n\n" +
"请检查微信公众平台的接口权限设置");
})
.body(String.class);
} catch (ApiException e) {
// ApiException直接抛出
throw e;
} catch (Exception e) {
System.err.println("调用微信API异常: " + e.getClass().getName());
System.err.println("异常信息: " + e.getMessage());
e.printStackTrace();
// 检查是否是412错误
if (e.getMessage() != null && e.getMessage().contains("412")) {
throw new ApiException(HttpStatus.BAD_GATEWAY, "WECHAT_ERROR",
"微信API返回412错误。\n\n" +
"可能原因:\n" +
"1. phoneCode已过期(有效期5分钟)或已被使用\n" +
"2. 服务器IP未加入微信公众平台IP白名单\n" +
"3. 请求体格式不符合微信要求\n\n" +
"请检查微信公众平台的接口权限设置");
}
// 其他网络异常
throw new ApiException(HttpStatus.BAD_GATEWAY, "WECHAT_ERROR",
"调用微信API失败: " + e.getMessage());
}
实在不知道啥问题,白名单啥的也设置了,求支援

解决了兄弟们,我改了一下httpcilent就好了。