public WxSimpleResult addKfAccountTest() {
// my_access_value 是我的 access_token 的值
String url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=my_access_value";
HttpHeaders httpHeaders = new HttpHeaders();
// Json 穿擦
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
// 第一中请求方式
HashMap<String, String> parameters = new HashMap<>();
// 我添加的客服微信的账号
parameters.put("kf_wx", "my_wx_account_value");
HttpEntity<HashMap<String, String>> entity = new HttpEntity<>(parameters, httpHeaders);
// class WxSimpleResult 对象字段结构如:{"errcode":0,"errmsg":"ok"}
ResponseEntity<WxSimpleResult> response = restTemplate.postForEntity(url, entity, WxSimpleResult.class);
// 第二种请求方式
MultiValueMap<Object, Object> body2 = new LinkedMultiValueMap<>();
body2.add("kf_wx", "my_wx_account_value");
HttpEntity<MultiValueMap<Object, Object>> entity2 = new HttpEntity<>(body2, httpHeaders);
ResponseEntity<WxSimpleResult> response2 = restTemplate.postForEntity(url, entity2, WxSimpleResult.class);
// 第三中请求方式,使用对象包装参数( AddKfRequest 类中字段 kf_wx,business_id)
AddKfRequest body3 = AddKfRequest.create("my_wx_account_value", null);
HttpEntity<AddKfRequest> entity3 = new HttpEntity<>(body3, httpHeaders);
ResponseEntity<WxSimpleResult> response3 = restTemplate.postForEntity(url, entity3, WxSimpleResult.class);
return null;
}
*** 以上三种参数封装方式传参 都响应 412 Precondition Failed: [no body] ***
// ####################### 参数和返回值实体类 #############################
// 返回值接收对象
@Getter
@Setter
public class WxSimpleResult implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 错误响应码,成功时返回 0
*
*/
private Integer errcode;
/**
* 错误响应消息,成功时返回 ok
*/
private String errmsg;
}
// 请求参数对象
@Getter
@Setter
public class AddKfRequest implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private String kf_wx;
private Integer business_id;
public static AddKfRequest create(String kfWx, String businessId) {
AddKfRequest addKfRequest = new AddKfRequest();
addKfRequest.setKf_wx(kfWx);
if (null != businessId && !businessId.isBlank()) {
addKfRequest.setBusiness_id(Integer.valueOf(businessId));
}
return addKfRequest;
}
}
代码截图如下:
********** 如上三种 参数封装的方式请求,均为异常响应 412 Precondition Failed: [no body] *********
最近遇到相同状态码错误, 找到原因是微信接口服务检查了body长度,我的情况是由于 header中 Transfer-Encoding 是trunked方式,导致计算不了body长度,在代码中保证不允许Transfer-Encoding 是trunked可解决