微信小程序发布需要校验敏感信息(内容、图片)-Java后端实现

news/2024/7/20 3:06:45 标签: java, http, 小程序, web, docker

精选30+云产品,助力企业轻松上云!>>> https://www.oschina.net/img/hot3.png" alt="hot3.png" />

前端只需要将图片和内容传过来即可

pom依赖

HttpClient的依赖和json转换的依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

封装Vo类

用于获取到access_token后进行转换,access_token是什么就不用我多说了吧

java">public class AccessTokenVO {
    private String access_token;
    private Integer expires_in;
    //记得给get set方法
}

封装工具类

java">import com.alibaba.fastjson.JSONObject;
import com.itheima.fete.pojo.AccessTokenVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * @author manlu
 */
public class SenInfoCheckUtil {
    /**
     * 图片违规检测,对外提供,直接使用
     *
     * @param accessToken
     * @param file
     * @return
     */
    public static Boolean imgFilter(String accessToken, MultipartFile file) {
        String contentType = file.getContentType();
        return checkPic(file, accessToken, contentType);
    }

    /**
     * 文本违规检测,对外提供,直接使用
     *
     * @param accessToken
     * @param content
     * @return
     */
    public static Boolean cotentFilter(String accessToken, String content) {
        return checkContent(accessToken, content);
    }

    /**
     * 校验图片是否有敏感信息
     *
     * @param multipartFile
     * @return
     */
    private static Boolean checkPic(MultipartFile multipartFile, String accessToken, String contentType) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/octet-stream");
            InputStream inputStream = multipartFile.getInputStream();
            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            request.setEntity(new ByteArrayEntity(byt, ContentType.create(contentType)));
            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();
            return true;
        }
    }

    /**
     * 校验内容是否有敏感信息
     * @param accessToken
     * @param content
     * @return
     */
    private static Boolean checkContent(String accessToken, 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=" + accessToken);
            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();
            return true;
        }
    }

    /**
     * 返回状态信息,可以修改为自己的逻辑
     * @param jso
     * @return
     */
    private static Boolean getResult(JSONObject jso) {
        Object errcode = jso.get("errcode");
        int errCode = (int) errcode;
        if (errCode == 0) {
            return true;
        } else if (errCode == 87014) {
            return false;
        } else {
            return false;
        }
    }

    /**
     * 获取小程序的 access_token
     * @return
     */
    public static String getAccessToken() {
        AccessTokenVO accessTokenVO = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            //改成自己的appid和secret
            HttpGet request = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbh0594d32gf315&secret=c9864f6e8aafg8313b6d5d608bd6a6b");
            request.addHeader("Content-Type", "application/json");
            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
            accessTokenVO = JSONObject.parseObject(result, AccessTokenVO.class);
            //返回token
            return accessTokenVO.getAccess_token();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

编写Controller层

java">import com.itheima.fete.utils.SenInfoCheckUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 漫路h
 * 校验内容是否敏感
 */
@RestController
@RequestMapping("/check")
public class CheckController {
    /**
     * 校验内容
     * @param content
     * @return
     * @throws IOException
     */
    @GetMapping("/content/{content}")
    public Boolean checkContent(@PathVariable String content) {
        String accessToken = SenInfoCheckUtil.getAccessToken();
        return SenInfoCheckUtil.cotentFilter(accessToken, content);
    }

    /**
     * 校验图片
     * @param multipartFile
     * @return
     */
    @PostMapping("/image")
    public Boolean checkImage(@RequestPart(value = "file") MultipartFile multipartFile){
        String accessToken = SenInfoCheckUtil.getAccessToken();
        return SenInfoCheckUtil.imgFilter(accessToken, multipartFile);
    }
}

如果不明白就问,如果需要uniapp代码的kou我


http://www.niftyadmin.cn/n/625901.html

相关文章

Java文件(File)、流(Stream)和IO

Java文件&#xff08;File&#xff09;、流&#xff08;Stream&#xff09;和IO Java的IO包中提供了所有操作输入、输出的类。所有这些类表示了输入源和输出目标。 一个流可以理解为一个数据的序列。输入流表示从一个源读取数据&#xff0c;输出流表示向一个目标写数据。 一…

使用uni-app获取微信小程序openid--Java后端实现

精选30云产品&#xff0c;助力企业轻松上云&#xff01;>>> 前言 这个是纯前端&#xff08;uniapp&#xff09;获取openid的&#xff1a;https://my.oschina.net/u/4284277/blog/3168782 但是这个有一个问题就是小程序正式上线后无法拿到openid&#xff0c;所以更新…

Java的多线程与并发编程

Java的多线程与并发编程 一、线程的实现 多线程创建 线程继承Thread类&#xff0c;实现run方法 public class Thread1 extends Thread {public void run(){//线程要执行的代码} }​ 线程实现Runnable接口&#xff0c;实现run方法 public class Thread1 implements Runnable {p…

解决:cannot deserialize from Object value (no delegate- or property-based Creator)

精选30云产品&#xff0c;助力企业轻松上云&#xff01;>>> com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of com.manlu.xxx.xxx (no Creators, like default construct, exist): cannot deserialize from Object v…

Java多线程和并发编程(续)

Java多线程和并发编程&#xff08;续&#xff09; 并行模式 主从模式&#xff08;Master-Slave&#xff09;Worker模式(Worker-Worker) Java并发编程 ExecutorFork-Join框架 一、Executor 分离任务的创建和执行者的创建 线程重复利用&#xff08;new线程代价很大&#xff09…

CSS与CSS3美化页面

CSS与CSS3美化页面 一、简介 CSS是&#xff08;Cascading Style Sheets&#xff09;&#xff0c;中文名叫层叠样式表。样式内定义的是如何显示HTML元素&#xff0c;目的是美化HTML页面样式通常储存在样式表中&#xff08;.css文件&#xff09;&#xff0c;实现了样式和内容分…

最详细的Java泛型知识点

Java泛型 一、 泛型&#xff08;Generic Programming&#xff09; 作用&#xff1a;编写的代码可以被很多不同类型的对象所重用 泛型类&#xff1a; ArrayList&#xff0c;HashSet&#xff0c;HashMap等泛型方法&#xff1a;Collections.binerySearch&#xff0c;Arrays.sor…

解决:If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.

精选30云产品&#xff0c;助力企业轻松上云&#xff01;>>> 错误日志 Description:Failed to configure a DataSource: url attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine a suitable driver classActio…