先哭诉一下,百度提供的API和当前版本不对称,让在下头疼了一个多小时,在此作文为大家使用提供参考。
一、引入sdk
<!--百度Api-->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>LATEST</version>
</dependency>
二、初始化应用参数
private static final String APP_ID = "xxxx";
private static final String API_KEY = "xxxx";
private static final String SECRET_KEY = "xxxx";
/**图片内容审核客户端*/
private static AipContentCensor contentCensorClient;
/**
* 初始化Client
*/
private static void getClient() {
//初始化图片审核客户端
contentCensorClient = new AipContentCensor(APP_ID, API_KEY, SECRET_KEY);
contentCensorClient.setConnectionTimeoutInMillis(2000);
contentCensorClient.setSocketTimeoutInMillis(60000);
// 初始化一个AipOcr
ocrClient = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
ocrClient.setConnectionTimeoutInMillis(2000);
ocrClient.setSocketTimeoutInMillis(60000);
}
三、审核文本内容
/**
* 识别文本中的敏感词汇(需要对百度API增强)
*
* @param text
*/
public static boolean discernSensitiveWords(String text, HashMap<String, String> options) {
String resp;
try {
//防止出现特殊符号,制造异常
resp = contentCensorClient.antiSpam(URLDecoder.decode(text, "UTF-8"), options).toString();
} catch (UnsupportedEncodingException e) {
return false;
}
//标识审核是否通过的结果所在未知
int len = resp.lastIndexOf("m\":") + 3;
String spam = resp.substring(len,len + 1);
//System.out.println(spam);
if(spam.equals("0")) {
return true;
}else {
return false;
}
}
四、审核图形内容
/**
* 识别图中的敏感内容(需要对百度API增强)
*
* @param image
*/
public static boolean discernSensitiveImage(byte[] image) throws IOException {
// 参数为本地图片文件二进制数组
String resp = contentCensorClient.imageCensorUserDefined(image, null).toString();
//截取conclusionType的值
String result = resp.substring(resp.length() - 2,resp.length()-1);
if (result.equals("1")) {
return true;
}else {
return false;
}
}
五、测试
public static void main(String[] args) throws IOException {
//文本内容审核
boolean result1 = discernSensitiveWords("共产党", null);
System.out.println("文本内容是否通过:" + result1);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//图片审核
InputStream inputStream = FileUtils.getInputStream("/file/test.jpg");
byte[] b = new byte[inputStream.available()];
inputStream.read(b);
boolean result2 = discernSensitiveImage(b);
System.out.println("图片内容是否通过:" + result2);
}