• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

java服务端实现微信小程序内容安全

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

请参考微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.imgSecCheck.html

可以使用“珊瑚内容安全助手”小程序测试该图片是否有违规,另外需要注意图片大小限制:1M

服务端代码如下(包含文字以及图片):

 

// 获取微信小程序配置信息
private static WechatConfig wechatConfig;

private static Integer CONNECTION_TIME_OUT = 3000;

@Autowired
public void setDatastore(WechatConfig WechatConfig) {
XcxSecCheckUtil.wechatConfig = WechatConfig;
}

// 获取token
public static String getAccessToken() throws UnsupportedEncodingException {
log.info("----------------开始----------------" + wechatConfig);
if (wechatConfig == null) {
throw new RuntimeException("wechatConfig is null");
}
log.info("----------------开步骤一+++---------------XcxAppId-" + wechatConfig.getXcxAppId());
log.info("----------------开步骤一+++---------------XcxAppSecret-" + wechatConfig.getXcxAppSecret());
String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wechatConfig.getXcxAppId() + "&secret=" +
wechatConfig.getXcxAppSecret();
log.info("----------------开步骤二+++----------------");
HttpResponse temp = HttpConnect.getInstance().doGetStr(URL);
log.info("----------------开步骤三+++----------------");
String tempValue = "";
String access_token = "";
log.info("temp:" + temp);
if (temp != null) {
tempValue = temp.getStringResult();
log.info("========" + tempValue + "=======");
JSONObject jsonObj = JSONObject.parseObject(tempValue);
if (jsonObj.containsKey("errcode")) {
log.info("获取微信access_token失败");
throw new RuntimeException("获取微信access_token失败");
}
access_token = jsonObj.getString("access_token");
}
return access_token;
}

/**
* 验证文字是否违规
*
* @param content
* @return
*/
public static Boolean checkContent(String content) {
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
//因服务器是内网把代理设置到请求配置 代理IP 端口
HttpHost proxy = new HttpHost(IP, port);
//超时时间单位为毫秒
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(CONNECTION_TIME_OUT)
.setProxy(proxy).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
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 = client.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 client = null;
CloseableHttpResponse response = null;
//把代理设置到请求配置 代理IP 端口
HttpHost proxy = new HttpHost(IP, port);
//超时时间单位为毫秒
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(CONNECTION_TIME_OUT)
.setProxy(proxy).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
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 = client.execute(request);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
JSONObject jso = JSONObject.parseObject(result);
log.info(jso + "-------------验证效果");
return getResult(jso);
} catch (Exception e) {
e.printStackTrace();
log.info("----------------调用腾讯内容过滤系统出错------------------");
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 {
// 代理的主机
Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress(IP, port));
HttpURLConnection conn = (HttpURLConnection)url.openConnection(proxy); //利用HttpURLConnection对象,我们可以从网络中获取网页数据.
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream(); //得到网络返回的输入流

} catch (IOException e) {
e.printStackTrace();
}
return is;
}


doget请求方式如下:
private static HttpConnect httpConnect = new HttpConnect();


public static HttpConnect getInstance() {
return httpConnect;
}

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();


public HttpResponse doGetStr(String url) {
String CONTENT_CHARSET = "UTF-8";
HttpClient client = new HttpClient(connectionManager);
// 代理的主机
ProxyHost proxy = new ProxyHost(IP, port);

// 使用代理
client.getHostConfiguration().setProxyHost(proxy);

client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,3000);
client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,3000);
client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
client.getHttpConnectionManager().getParams().setSoTimeout(3000);
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);
HttpMethod method = new GetMethod(url);
HttpResponse response = new HttpResponse();
try {
client.executeMethod(method);
response.setStringResult(method.getResponseBodyAsString());
} catch (HttpException e) {
log.info(e.getMessage());
method.releaseConnection();
return null;
} catch (IOException e) {
log.info(e.getMessage());
method.releaseConnection();
return null;
}
return response;
}


对HttpResponse进行改善:
private Header[] responseHeaders;

private String stringResult;

private byte[] byteResult;

public Header[] getResponseHeaders() {
return responseHeaders;
}

public void setResponseHeaders(Header[] responseHeaders) {
this.responseHeaders = responseHeaders;
}

public byte[] getByteResult() {
if (byteResult != null) {
return byteResult;
}
if (stringResult != null) {
return stringResult.getBytes();
}
return null;
}

public void setByteResult(byte[] byteResult) {
this.byteResult = byteResult;
}

public String getStringResult() throws UnsupportedEncodingException {
if (stringResult != null) {
return stringResult;
}
if (byteResult != null) {
return new String(byteResult,"utf-8");
}
return null;
}

public void setStringResult(String stringResult) {
this.stringResult = stringResult;
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
微信小程序中的上拉加载发布时间:2022-07-18
下一篇:
《微信小程序七日谈》- 第三天:玩转Page组件的生命周期发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap