1. 程式人生 > 實用技巧 >java服務端實現微信小程式內容安全

java服務端實現微信小程式內容安全

請參考微信官方文件: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;
}