springboot整合百度AI的图片和文字违规识别

调用百度AI的图片和文字违规识别

一、需要从百度AI开放平台下载依赖,导入依赖后,创建百度AI的properties文件

文件名:BaiDuAi.properties

baidu.API_KEY = ****
baidu.SECRET_KEY = *****

二、加载配置文件类

文件名:BaiduAiConfig

import lombok.Data;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@PropertySource("classpath:BaiDuAi.properties")
public class BaiduAiConfig{
    private String appkey;
    private String secretkey;
}

三、创建httputil类并设置ContentType为application/x-www-form-urlencoded

HttpClientUtils

    public static JSONObject  doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                //设置ContentType为application/x-www-form-urlencoded
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 请求发送成功,并得到响应

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

            {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                JSONObject jsonObject = JSONObject.parseObject(strResult);
                return jsonObject;
            }
            else
            {
                logger.error("get请求提交失败:" + url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

四、封装一个util类,分别加入以下代码

获取accesstoken 调用百度AI都必须要这个accesstoken ,每获取一次在百度ai会存储20天左右, 为了避免不必要的请求,建议存到redis中,先从redis中获取,等过期后再通过调用接口获取

//    获取accesstoken
    public String getaccesstoken(String appkey,String secretkey){
        try {
            JSONObject jsonObject = HttpClientUtils.httpGet("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+appkey+"&client_secret="+secretkey);
            String accesstoken = jsonObject.getString("access_token");
            return accesstoken;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

请求文本审核接口

//    文本审核
    public JSONObject textcensorString(String accesstoken,String text){
        try {
            Map<String, String> param = new HashMap<>();
            param.put("text",text);
            JSONObject jsonObject = HttpClientUtils.doPost("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token="+accesstoken, param);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

处理文本审核返回的json(这个可根据自己的需求来)

    public JSONObject textcensorname(JSONObject obj, JedisClient jedisClient,BaiduAiConfig baiduAiConfig) throws Throwable {
        String getaccesstoken = jedisClient.get("BAIDUAO_TOCKEN");
        if(getaccesstoken==null){
            getaccesstoken=getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        JSONObject jsonObject = textcensorString(getaccesstoken,obj.toJSONString());
        if(jsonObject.getInteger("error_code")!=null&&110==(jsonObject.getInteger("error_code"))||jsonObject.getInteger("error_code")!=null&&111==(jsonObject.getInteger("error_code"))){
            getaccesstoken = getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jsonObject = textcensorString(getaccesstoken,obj.toJSONString());
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        return jsonObject;
    }

请求图片审核接口

//    图片审核
    public JSONObject imgcensorString(String accesstoken,String base64EncoderImg){
        try {
            Map<String, String> param = new HashMap<>();
            param.put("image",base64EncoderImg);
            JSONObject jsonObject = HttpClientUtils.doPost("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token="+accesstoken, param);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

图片转base64

    public String multipartFileToBASE64(MultipartFile mFile) throws Exception{
        BASE64Encoder bEncoder=new BASE64Encoder();
        String[] suffixArra=mFile.getOriginalFilename().split("\\.");
     /*   String preffix="data:image/jpg;base64,".replace("jpg", suffixArra[suffixArra.length - 1]);*/
        String base64EncoderImg=bEncoder.encode(mFile.getBytes()).replaceAll("[\\s*\t\n\r]", "");

        return base64EncoderImg;
    }

处理图片审核返回的json (这个可根据自己的需求来)

    public Boolean imgcensorname(String base64EncoderImg, JedisClient jedisClient,BaiduAiConfig baiduAiConfig) throws Throwable {
        String getaccesstoken = jedisClient.get("BAIDUAO_TOCKEN");
        if(getaccesstoken==null){
            getaccesstoken=getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        JSONObject jsonObject = imgcensorString(getaccesstoken,base64EncoderImg);
        if(jsonObject.getInteger("error_code")!=null&&110==(jsonObject.getInteger("error_code"))||jsonObject.getInteger("error_code")!=null&&111==(jsonObject.getInteger("error_code"))){
            getaccesstoken = getaccesstoken(baiduAiConfig.getAppkey(), baiduAiConfig.getSecretkey());
            jsonObject = textcensorString(getaccesstoken,base64EncoderImg);
            jedisClient.set("BAIDUAO_TOCKEN",getaccesstoken);
        }
        System.out.println(jsonObject);
        if(2==(jsonObject.getInteger("conclusionType"))){

            return false;
        }
        return true;
    }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值