java服务端实现微信小程序内容安全
可以使用“珊瑚内容安全助手”小程序测试该图片是否有违规,另外需要注意图片大小限制: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;
}