最近这几天做小程序的项目,审批的时候因为没有做文本内容监测,所以审核不通过,翻了下官方API,然后在博客上看了别人分享的,算是搬出来一套可以用的代码,在这里给大家分享一下。首先是官方API :https://developers./miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html检测图片 文本内容都需要Access_Token这个参数,所以在调用链接之前要先获取Token,因为这个小程序用户量不是很大,所以暂时没有存redis,方法献上。
//获取access_tokenpublic static Map<String, Object> getAccessToken() {Map<String, Object> map = null;StringBuffer url = new StringBuffer("https://api./cgi-bin/token?grant_type=client_credential");url.append("&appid=");//appid设置url.append(APPID);url.append("&secret=");//secret设置url.append(APPSecret);try {HttpClient client =HttpClientBuilder.create().build();//构建一个ClientHttpGet get = new HttpGet(url.toString()); //构建一个GET请求HttpResponse response = client.execute(get);//提交GET请求HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"String content = EntityUtils.toString(result); JSONObject res = JSONObject.fromObject(content);//把信息封装为json//把信息封装到mapmap = parseJSON2Map(res);} catch (Exception e) {e.printStackTrace();}return map;}//json转mappublic static Map<String, Object> parseJSON2Map(JSONObject json) {Map<String, Object> map = new HashMap<String, Object>();// 最外层解析for (Object k : json.keySet()) {Object v = json.get(k);// 如果内层还是数组的话,继续解析if (v instanceof JSONArray) {List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();@SuppressWarnings("unchecked")Iterator<JSONObject> it = ((JSONArray) v).iterator();while (it.hasNext()) {JSONObject json2 = it.next();list.add(parseJSON2Map(json2));}map.put(k.toString(), list);} else {map.put(k.toString(), v);}}return map;}//校验文本内容是否有违法违规内容public static Boolean checkText(String accessToken,String textConetnt) {try {CloseableHttpClient httpclient = HttpClients.createDefault();CloseableHttpResponse response = null;HttpPost request = new HttpPost("https://api./wxa/msg_sec_check?access_token=" + accessToken);request.addHeader("Content-Type", "application/json;charset=UTF-8");Map<String, String> paramMap = new HashMap<String, String>();paramMap.put("content", textConetnt);request.setEntity(new StringEntity(com.alibaba.fastjson.JSONObject.toJSONString(paramMap), ContentType.create("application/json", "utf-8")));response = httpclient.execute(request);HttpEntity httpEntity = response.getEntity();String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成stringcom.alibaba.fastjson.JSONObject jso = com.alibaba.fastjson.JSONObject.parseObject(result);System.out.println(jso);Object errcode = jso.get("errcode");int errCode = (int) errcode;if (errCode == 0) {return true;} else if (errCode == 87014) {System.out.println("内容违规-----------" + textConetnt);return false;}return true;} catch (Exception e) {e.printStackTrace();System.out.println("----------------调用腾讯内容过滤系统出错------------------");return true;}}
以上就是校验文本内容是否违规的方法,接下来是校验图片
/*** 图片过滤检测* @param file 图片文件* @return*/@RequestMapping(value = "/imgcheck", method = {RequestMethod.POST})@ResponseBodypublic AccessTokenWX checkPic(@RequestParam(value = "file") MultipartFile file, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {//自己写一个定时任务或其他方式 获取AccessTokenAccessTokenWX accessTokenWX = new AccessTokenWX();try {String token = WxApiUtil.getAccessToken().get("access_token")+"";String url = "https://api./wxa/img_sec_check?access_token=" + token;String result = WxApiUtil.uploadFile(url, file);accessTokenWX = JSON.parseObject(result, AccessTokenWX.class);System.out.println("图片检测结果 = " + result);return accessTokenWX;} catch (Exception e) {accessTokenWX.setErrcode("500");accessTokenWX.setErrmsg("system错误");return accessTokenWX;}}/*** 上传二进制文件* @param graphurl 接口地址* @param file 图片文件* @return*/public static String uploadFile(String graphurl,MultipartFile file) {String line = null;//接口返回的结果try {// 换行符final String newLine = "\r\n";final String boundaryPrefix = "--";// 定义数据分隔线String BOUNDARY = "========7d4a6d158c9";// 服务器的域名URL url = new URL(graphurl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 设置为POST情conn.setRequestMethod("POST");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);// 设置请求头参数conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");OutputStream out = new DataOutputStream(conn.getOutputStream());// 上传文件StringBuilder sb = new StringBuilder();sb.append(boundaryPrefix);sb.append(BOUNDARY);sb.append(newLine);// 文件参数,photo参数名可以随意修改sb.append("Content-Disposition: form-data;name=\"image\";filename=\""+ "https://api." + "\"" + newLine);sb.append("Content-Type:application/octet-stream");// 参数头设置完以后需要两个换行,然后才是参数内容sb.append(newLine);sb.append(newLine);// 将参数头的数据写入到输出流中out.write(sb.toString().getBytes());// 读取文件数据out.write(file.getBytes());// 最后添加换行out.write(newLine.getBytes());// 定义最后数据分隔线,即--加上BOUNDARY再加上--。byte[] end_data = (newLine + boundaryPrefix + BOUNDARY+ boundaryPrefix + newLine).getBytes();// 写上结尾标识out.write(end_data);out.flush();out.close();// 定义BufferedReader输入流来读取URL的响应BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));while ((line = reader.readLine()) != null) {return line;}} catch (Exception e) {System.out.println("发送POST请求出现异常!" + e);}return line;}@JsonInclude(JsonInclude.Include.NON_NULL)public class AccessTokenWX {private String access_token;private Integer expires_in;private String errcode;private String errmsg;public String getAccess_token() {return access_token;}public void setAccess_token(String access_token) {this.access_token = access_token;}public Integer getExpires_in() {return expires_in;}public void setExpires_in(Integer expires_in) {this.expires_in = expires_in;}public String getErrcode() {return errcode;}public void setErrcode(String errcode) {this.errcode = errcode;}public String getErrmsg() {return errmsg;}public void setErrmsg(String errmsg) {this.errmsg = errmsg;} }
以上代码搬完,图片和文本的内容检验就完事了,附上参考博客
检验文本内容是否违法:/leisure_life/article/details/93881235
检验图片内容是否违法:/xshuai/blog/3112651
微信小程序常见返回码:/webonline/p/7528778.html
如果觉得《微信小程序监测文本内容 图片内容是否包含违法违规内容》对你有帮助,请点赞、收藏,并留下你的观点哦!