首先分两个重要点
①:请求 url 要携带 access_token (文档并未提醒)
②:要以 raw 方式提交
下面我们以 微信小程序开发工具 和s pring boot 的两个例子进行演示。
如果使用微信小程序开发工具,请首先选择 不校验合法域名。
此功能仅限于本地测试,并且在在线发布时仍需要进行验证。 (这仅是为了测试的理解,后台将在下面介绍)
错误请求(仅仅相对于某些特定问题来说;如:47001)
wx.request({
url: "https://api.weixin.qq.com/wxa/msg_sec_check",
data: {
access_token:"XXXXXX"
content:"文本审核",
},
method: 'POST',
//请求头
header: {
'content-type': 'application/x-www-form-urlencoded' },
success: function (res) {
console.log(res)
},
})
正确请求(仅仅相对于某些特定问题来说;如:47001)
wx.request({
url: "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=xxxxx",
data: {
content:"文本审核"
},
method: 'POST',
success: function (res) {
console.log(res)
},
})
仔细对比一下他们两个写法的不同点。
在这里,我们使用Spring Boot的RestTemplate测试。
这是 RestTemplate发送请求教程
错误写法(仅仅相对于某些特定问题来说;如:47001)
public SecCheck get_msgSecCheck(String access_token,String content ){
String url = "https://api.weixin.qq.com/wxa/msg_sec_check";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("access_token",content);
paramMap.put("content",content);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);
System.out.println(httpEntity);
ResponseEntity<SecCheck> response = this.restTemplate.postForEntity(url, httpEntity, SecCheck.class);
return response.getBody();
}
正确写法(仅仅相对于某些特定问题来说;如:47001)
public SecCheck get_msgSecCheck(String access_token,String content ){
String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+access_token;
Map<String, String> paramMap = new HashMap<>();
paramMap.put("content",content);
HttpHeaders headers = new HttpHeaders();
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);
System.out.println(httpEntity);
ResponseEntity<SecCheck> response = this.restTemplate.postForEntity(url, httpEntity, SecCheck.class);
return response.getBody();
}
第一个原因自然是文档 通(sang)俗(xin)易(bing)懂(kuang)
第二个原因是 请求头
我们看一下 post 常用请求 Content-Type 类型
①:application/x-www-form-urlencoded
最常见的 POST 提交数据的方式,表单内的数据将会被转换为键值对方式提交,如 name=anny&age = 20。
②:multipart/form-data
它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开。既可以上传键值对,也可以上传文件。
③:raw
可以上传任意格式的文本,可以上传text、json、xml、html等。