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;
}
java服务端实现微信小程序内容安全的更多相关文章
- 用 React 编写的基于Taro + Dva构建的适配不同端(微信小程序、H5、React-Native 等)的时装衣橱
前言 Taro 是一套遵循 React 语法规范的 多端开发 解决方案.现如今市面上端的形态多种多样,Web.React-Native.微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表 ...
- 从0到1构建适配不同端(微信小程序、H5、React-Native 等)的taro + dva应用
从0到1构建适配不同端(微信小程序.H5.React-Native 等)的taro + dva应用 写在前面 Taro 是一套遵循 React 语法规范的 多端开发 解决方案.现如今市面上端的形态多种 ...
- 微信小程序内容组件图标 icon
小程序内置了一下图标可以用 需要自定义图标的看这里 ==>微信小程序中使用iconfont/font-awesome等自定义字体图标 小程序内置图标使用示例 <icon type=&quo ...
- appium+java(五)微信小程序自动化测试实践
前言: 上一篇<appium+java(四)微信公众号自动化测试实践>中,尝试使用appium实现微信公众号自动化测试,接着尝试小程序自动化,以学院小程序为例 准备工作 1.java-cl ...
- 基于jsoup的Java服务端http(s)代理程序-代理服务器Demo
亲爱的开发者朋友们,知道百度网址翻译么?他们为何能够翻译源网页呢,iframe可是不能跨域操作的哦,那么可以用代理实现.直接上代码: 本Demo基于MVC写的,灰常简单,copy过去,简单改改就可以用 ...
- 微信小程序,内容组件中兼容的H5组件
受信任的HTML节点及属性 全局支持class和style属性,不支持id属性. 节点 属性 a abbr address article aside b bdi bdo ...
- 微信小程序访问webservice(wsdl)+ axis2发布服务端(Java)
0.主要思路:使用axis2发布webservice服务端,微信小程序作为客户端访问.步骤如下: 1.服务端: 首先微信小程序仅支持访问https的url,且必须是已备案域名.因此前期的服务器端工作需 ...
- C#开发微信小程序
个人见解,欢迎交流,不喜勿喷. 微信小程序相比于微信公众号的开发,区别在于微信小程序只请求第三方的数据,整个界面的交互(view)还是在微信小程序上实现,前后端完全分离,说白了,微信小程序开发与具 ...
- uniapp保存图片到本地(APP和微信小程序端)
uniapp实现app端和微信小程序端图片保存到本地,其它平台未测过,原理类似. 微信小程序端主要是权限需要使用button的开放能力来反复调起,代码如下: 首先是条件编译两个平台的按钮组件: < ...
随机推荐
- 错误记录:MIME type may not contain reserved characters
最近遇到个问题,随手记录一下! 新做了一个项目,要通过HTTP请求发送ZIP文件到OSS平台,但上传过程中,总是出现下面错误提示: 初步判定,应该是包冲突原因!于是,分析MIME-TYPE获取源码发现 ...
- HTTP Request Method(十五种)
序号 方法 描述 1 GET 请求指定的页面信息,并返回实体主体. 2 HEAD 类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头 3 POST 向指定资源提交数据进行处理请求(例如提 ...
- 基于DispatchProxy打造自定义AOP组件
DispatchProxy是微软爸爸编写的一个代理类,基于这个,我扩展了一个AOP组件 暂时不支持依赖注入构造方法,感觉属性注入略显麻烦,暂时没打算支持 基于特性的注入流程 [AttributeUsa ...
- day22:面向对象封装对象操作&类操作&面向对象删除操作
面向对象程序开发 1.类的三种定义方式 class MyClass: pass class MyClass(): #(推荐) pass class MyClass(object): # object类 ...
- Node.js 和 Python之间如何进行选择?
转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 原文出处:https://dzone.com/articles/nodejs-vs-python-which ...
- Python turtle库的画笔控制说明
turtle.penup() 别名 turtle.pu() :抬起画笔海龟在飞行 turtle.pendown() 别名 turtle.pd():画笔落下,海龟在爬行 turtle.pensize(w ...
- JS DOM重点核心笔记
DOM重点核心 文档对象模型,是W3C推荐的处理可扩展的标记语言的标准编程接口 我们主要针对与勇士的操作,主要有创建.增加.删除.修改.查询.属性操作.事件操作 三种动态创建元素的 ...
- 2020-07-10:sql如何调优?
福哥答案2020-07-10:此答案来自群成员: SQL提高查询效率的几点建议 1.如果要用子查询,那就用EXISTS替代IN.用NOT EXISTS替代NOT IN.因为EXISTS引入的子查询只是 ...
- Visual Studio 2019预览,净生产力
本文章为机器翻译. https://blogs.msdn.microsoft.com/dotnet/2018/12/13/visual-studio-2019-net-productivity/ 该文 ...
- C#LeetCode刷题之#55-跳跃游戏(Jump Game)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3674 访问. 给定一个非负整数数组,你最初位于数组的第一个位置. ...