微信小程序 图片 文字 敏感内容验证 获取小程序accessToken

直接上代码:代码中有解释。

一下是验证文字的静态方法直接调用就行。

//文字安全检测  (accessToken是微信小程序的APPID和scret获取的)
    public static  Boolean msgSecCheck(String str,String accessToken){


        String msgSecCheckUrl = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+accessToken;

        HashMap map = new HashMap();
        map.put("content", str);

//   发送post网络请求见下一篇文章
        String res = HttpRequest.sendPost(msgSecCheckUrl,  JSONObject.fromMap(map).toString());

        JSONObject json = JSONObject.fromString(res);
        System.out.println(accessToken);
        System.out.println(json);

        int errcode = json.has("errcode")?json.getInt("errcode"):-1;

        if(errcode!=0){
            return false;
        }

        return true;
    }

图片安全验证

//图片安全检测
    public static  Boolean imgSecCheck(MultipartFile multipartFile, String accessToken) {
        try {

            CloseableHttpClient httpclient = HttpClients.createDefault();

            CloseableHttpResponse response = null;

            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/octet-stream");


            InputStream inputStream = multipartFile.getInputStream();

            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));


            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string


            JSONObject jso = JSONObject.fromString(result);

            int errcode = jso.has("errcode")?jso.getInt("errcode"):-1;

            if (errcode == 0) {
                return true;
            } else if (errcode == 87014) {
                System.out.println("图片内容违规-----------");
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("----------------调用腾讯内容过滤系统出错------------------");
            return true;
        }
    }

accessToken获取方法:

public static   String createToken(String appId,String secret) {

		System.out.println("进入方法getToken");
		String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
		StringBuffer param = new StringBuffer("grant_type=client_credential");
		param.append("&").append("appid="+appId);
		param.append("&").append("secret="+secret);
		String res = HttpRequest.sendGet(tokenUrl,param.toString());

		JSONObject json = JSONObject.fromString(res);

		String access_token = json.has("access_token")?json.getString("access_token"):"";
		System.out.println(access_token);
		return access_token;
	}

 

你可能感兴趣的:(微信小程序)