根据微信官方文档写了份适合的小程序敏感内容检查代码
直接上代码
// 获取token
public static String getAccessToken()
{
String appId= "自己的";
String secret="自己的";
String accessToken="https://api.weixin.qq.com/cgi-bin/token";
String turl = String.format(
"%s?grant_type=client_credential&appid=%s&secret=%s", accessToken,
appId, secret);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(turl);
JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
String result = null;
try
{
HttpResponse res = client.execute(get);
String responseContent = null; // 响应内容
HttpEntity entity = res.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
JsonObject json = jsonparer.parse(responseContent)
.getAsJsonObject();
// 将json字符串转换为json对象
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
if (json.get("errcode") != null)
{// 错误时微信会返回错误码等信息,{"errcode":40013,"errmsg":"invalid appid"}
}
else
{// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
result = json.get("access_token").getAsString();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// 关闭连接 ,释放资源
client.getConnectionManager().shutdown();
return result;
}
}
/**
* 验证文字是否违规
* @param content
* @return
*/
public static Boolean checkContent(String content) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + getAccessToken());
request.addHeader("Content-Type", "application/json");
Map<String, String> map = new HashMap<>();
map.put("content",content);
String body = JSONObject.toJSONString(map);
request.setEntity(new StringEntity(body,ContentType.create("text/json", "UTF-8")));
response = httpclient.execute(request);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
JSONObject jso = JSONObject.parseObject(result);
return getResult(jso);
} catch (Exception e) {
e.printStackTrace();
log.info("----------------调用腾讯内容过滤系统出错------------------");
return true;
}
}
private static Boolean getResult(JSONObject jso){
Object errcode = jso.get("errcode");
int errCode = (int) errcode;
if (errCode == 0) {
return true;
} else if (errCode == 87014) {
log.info("图片内容违规-----------");
return false;
}
return true;
}
/**
* 恶意图片过滤
* @return
*/
public static Boolean checkPick(String images) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + getAccessToken());
request.addHeader("Content-Type", "application/octet-stream");
InputStream inputStream = returnBitMap(images);
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.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("图片内容违规-----------");
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("----------------调用腾讯内容过滤系统出错------------------");
return true;
}
}
/**
* 通过图片url返回图片Bitmap
* @param path
* @return
*/
public static InputStream returnBitMap(String path) {
URL url = null;
InputStream is =null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream(); //得到网络返回的输入流
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
工具类
/**
* 数组转list
* @param blise
* @return
*/
public static List<String> arrayToList(String blise) throws Exception{
String str2 = blise.substring(1, blise.length());
String strs=str2.substring(0,str2.length()-1);
String[] strArr = strs.split(",");//注意分隔符是需要转译
List<String> urls=new ArrayList<>();
for (int i = 0; i < strArr.length; i++) {
String str3 = strArr[i].substring(1, strArr[i].length());
String str4=str3.substring(0,str3.length()-1);
urls.add(str4);
}
return urls;
}
测试类
public static void main(String...args) throws ParseException {
String image="[\"http://jsyxt.szjishiyi.com/test.jpg\",\"http://jsyxt.szjishiyi.com/testtwo.png\"]";//无多张图可自己省略该步骤,
String context="特3456书yuuo莞6543李zxcz蒜7782法fgnv级\n" +
"完2347全dfji试3726测asad感3847知qwez到";
List<String> images= null;
try {
images = com.platform.utils.ArrayToList.arrayToList(image);
} catch (Exception e) {
e.printStackTrace();
}
images.forEach(a->{
if(!checkPick(a)){
//R.error("图片内容违规");
System.out.println("is bad");
}else {
System.out.println("is ok");
}
});
if(checkContent(context)) {
System.out.println("context is ok");
}else {
System.out.println("context is bad");
}
}
本文介绍了一种基于微信官方API的小程序敏感内容检测方法,包括获取access_token、文本和图片内容违规检查的实现细节。
1620

被折叠的 条评论
为什么被折叠?



