图片审核 文本审核测试类
This commit is contained in:
28
pom.xml
28
pom.xml
@@ -73,6 +73,34 @@
|
|||||||
<version>1.2.83</version>
|
<version>1.2.83</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.6.3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-green</artifactId>
|
||||||
|
<version>3.4.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>imageaudit20191230</artifactId>
|
||||||
|
<version>2.0.6</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>tea-openapi</artifactId>
|
||||||
|
<version>0.2.8</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>teautil</artifactId>
|
||||||
|
<version>0.2.16</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|||||||
108
src/main/java/com/bao/dating/common/aliyun/GreenImageScan.java
Normal file
108
src/main/java/com/bao/dating/common/aliyun/GreenImageScan.java
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package com.bao.dating.common.aliyun;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.aliyun.imageaudit20191230.models.ScanImageRequest;
|
||||||
|
import com.aliyun.imageaudit20191230.models.ScanImageResponse;
|
||||||
|
import com.aliyun.imageaudit20191230.models.ScanImageResponseBody;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "aliyun")
|
||||||
|
public class GreenImageScan {
|
||||||
|
|
||||||
|
private String accessKeyId;
|
||||||
|
private String secret;
|
||||||
|
private String scenes;
|
||||||
|
|
||||||
|
public Map imageScan(List<String> imageList) throws Exception {
|
||||||
|
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
|
||||||
|
.setAccessKeyId(accessKeyId)
|
||||||
|
.setAccessKeySecret(secret);
|
||||||
|
// 访问的域名
|
||||||
|
config.endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
|
||||||
|
|
||||||
|
com.aliyun.imageaudit20191230.Client client = new com.aliyun.imageaudit20191230.Client(config);
|
||||||
|
|
||||||
|
List<ScanImageRequest.ScanImageRequestTask> taskList = new ArrayList<>();
|
||||||
|
|
||||||
|
for (String img: imageList) {
|
||||||
|
ScanImageRequest.ScanImageRequestTask task = new ScanImageRequest.ScanImageRequestTask();
|
||||||
|
task.setImageURL(img); // 修复:直接使用图片URL而不是转换为字符数组 task.setDataId(UUID.randomUUID().toString());
|
||||||
|
task.setImageTimeMillisecond(1L);
|
||||||
|
task.setInterval(1);
|
||||||
|
task.setMaxFrames(1);
|
||||||
|
taskList.add(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//场景
|
||||||
|
List<String> sceneList = new ArrayList<>();
|
||||||
|
// 移除了不支持的"antispam"场景,使用支持的场景
|
||||||
|
sceneList.add("porn"); // 涉黄识别
|
||||||
|
sceneList.add("terrorism"); // 暴恐识别
|
||||||
|
sceneList.add("ad"); // 图片广告
|
||||||
|
sceneList.add("live"); // 不良场景
|
||||||
|
sceneList.add("logo"); // logo识别
|
||||||
|
|
||||||
|
com.aliyun.imageaudit20191230.models.ScanImageRequest scanImageRequest = new com.aliyun.imageaudit20191230.models.ScanImageRequest()
|
||||||
|
.setTask(taskList)
|
||||||
|
.setScene(sceneList);
|
||||||
|
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
|
||||||
|
try {
|
||||||
|
ScanImageResponse scanImageResponse = client.scanImageWithOptions(scanImageRequest, runtime);
|
||||||
|
Map<String, String> resultMap = new HashMap<>();
|
||||||
|
|
||||||
|
if (scanImageResponse.getStatusCode() == 200) {
|
||||||
|
|
||||||
|
List<ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults> subResults = scanImageResponse.body.data.results.get(0).getSubResults();
|
||||||
|
|
||||||
|
ListIterator<ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults> listIterator = subResults.listIterator();
|
||||||
|
while (listIterator.hasNext()) {
|
||||||
|
ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults item = listIterator.next();
|
||||||
|
/* System.out.println("scene = [" + item.scene + "]");
|
||||||
|
System.out.println("suggestion = [" + item.suggestion + "]");
|
||||||
|
System.out.println("label = [" + item.label + "]");*/
|
||||||
|
|
||||||
|
if (!item.suggestion.equals("pass")) {
|
||||||
|
resultMap.put("suggestion", item.suggestion);
|
||||||
|
resultMap.put("label", item.label);
|
||||||
|
return resultMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 所有审核项都通过时,返回pass结果
|
||||||
|
resultMap.put("suggestion", "pass");
|
||||||
|
resultMap.put("label", "normal");
|
||||||
|
return resultMap;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
/* *
|
||||||
|
* 表明请求整体处理失败,原因视具体的情况详细分析
|
||||||
|
*/
|
||||||
|
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scanImageResponse));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
} catch (com.aliyun.tea.TeaException teaException) {
|
||||||
|
// 获取整体报错信息
|
||||||
|
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
|
||||||
|
// 获取单个字段
|
||||||
|
System.out.println(teaException.getCode());
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Map<String, String> resultMap = new HashMap<>();
|
||||||
|
resultMap.put("suggestion", "pass");
|
||||||
|
return resultMap;*/
|
||||||
|
}
|
||||||
|
}
|
||||||
127
src/main/java/com/bao/dating/common/aliyun/GreenTextScan.java
Normal file
127
src/main/java/com/bao/dating/common/aliyun/GreenTextScan.java
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
package com.bao.dating.common.aliyun;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.aliyun.green20220302.Client;
|
||||||
|
import com.aliyun.green20220302.models.TextModerationRequest;
|
||||||
|
import com.aliyun.green20220302.models.TextModerationResponse;
|
||||||
|
import com.aliyun.green20220302.models.TextModerationResponseBody;
|
||||||
|
import com.aliyun.teaopenapi.models.Config;
|
||||||
|
import com.aliyun.teautil.models.RuntimeOptions;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "aliyun")
|
||||||
|
public class GreenTextScan {
|
||||||
|
|
||||||
|
|
||||||
|
private String accessKeyId;
|
||||||
|
private String secret;
|
||||||
|
|
||||||
|
public Map greeTextScan(String content) throws Exception {
|
||||||
|
// accessKeyId = "LTAI5tKo9TpWH1aW6JxWm1Gp";
|
||||||
|
// secret = "LHk9DdHECKCwIdaIM9fkGgEuowt18W";
|
||||||
|
Config config = new Config();
|
||||||
|
config.setAccessKeyId(accessKeyId);
|
||||||
|
config.setAccessKeySecret(secret);
|
||||||
|
//接入区域和地址请根据实际情况修改
|
||||||
|
config.setRegionId("cn-shanghai");
|
||||||
|
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
|
||||||
|
//连接时超时时间,单位毫秒(ms)。
|
||||||
|
config.setReadTimeout(6000);
|
||||||
|
//读取时超时时间,单位毫秒(ms)。
|
||||||
|
config.setConnectTimeout(3000);
|
||||||
|
Client client = new Client(config);
|
||||||
|
|
||||||
|
// 创建RuntimeObject实例并设置运行参数。
|
||||||
|
RuntimeOptions runtime = new RuntimeOptions();
|
||||||
|
runtime.readTimeout = 10000;
|
||||||
|
runtime.connectTimeout = 10000;
|
||||||
|
|
||||||
|
//检测参数构造
|
||||||
|
JSONObject serviceParameters = new JSONObject();
|
||||||
|
serviceParameters.put("content", content);
|
||||||
|
|
||||||
|
//检测结果构造
|
||||||
|
Map<String,String> resultMap = new HashMap<>();
|
||||||
|
if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
|
||||||
|
|
||||||
|
resultMap.put("suggestion","检测内容为空");
|
||||||
|
System.out.println("text moderation content is empty");
|
||||||
|
return resultMap;
|
||||||
|
}
|
||||||
|
TextModerationRequest textModerationRequest = new TextModerationRequest();
|
||||||
|
/*
|
||||||
|
文本检测service:内容安全控制台文本增强版规则配置的serviceCode,示例:chat_detection
|
||||||
|
*/
|
||||||
|
textModerationRequest.setService("comment_detection");
|
||||||
|
textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
// 调用方法获取检测结果。
|
||||||
|
TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
|
||||||
|
|
||||||
|
// 自动路由。
|
||||||
|
if (response != null) {
|
||||||
|
|
||||||
|
// 服务端错误,区域切换到cn-beijing。
|
||||||
|
if (500 == response.getStatusCode()) {
|
||||||
|
|
||||||
|
// 接入区域和地址请根据实际情况修改。
|
||||||
|
config.setRegionId("cn-beijing");
|
||||||
|
config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
|
||||||
|
client = new Client(config);
|
||||||
|
response = client.textModerationWithOptions(textModerationRequest, runtime);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
// 打印检测结果。
|
||||||
|
if (response != null) {
|
||||||
|
|
||||||
|
if (response.getStatusCode() == 200) {
|
||||||
|
|
||||||
|
TextModerationResponseBody result = response.getBody();
|
||||||
|
System.out.println(JSON.toJSONString(result));
|
||||||
|
// 直接使用JSON解析来获取code值,避免类型不匹配问题
|
||||||
|
JSONObject resultJson = JSON.parseObject(JSON.toJSONString(result));
|
||||||
|
String code = resultJson.getString("code");
|
||||||
|
|
||||||
|
if (code != null && "200".equals(code)) {
|
||||||
|
|
||||||
|
TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
|
||||||
|
if (data.getLabels().isEmpty() && data.getReason().isEmpty()) {
|
||||||
|
|
||||||
|
resultMap.put("suggestion", "pass");
|
||||||
|
}else {
|
||||||
|
|
||||||
|
resultMap.put("suggestion","block");
|
||||||
|
resultMap.put("labels",data.getLabels());
|
||||||
|
resultMap.put("reason", data.getReason());
|
||||||
|
}
|
||||||
|
System.out.println("labels = [" + data.getLabels() + "]");
|
||||||
|
System.out.println("reason = [" + data.getReason() + "]");
|
||||||
|
} else {
|
||||||
|
|
||||||
|
System.out.println("text moderation not success. code:" + code);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
|
||||||
|
System.out.println("response not success. status:" + response.getStatusCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return resultMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package com.bao.dating.common.aliyun.util;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.aliyun.oss.OSSClient;
|
||||||
|
import com.aliyun.oss.model.ObjectMetadata;
|
||||||
|
import com.aliyun.oss.model.PutObjectResult;
|
||||||
|
import com.aliyuncs.DefaultAcsClient;
|
||||||
|
import com.aliyuncs.IAcsClient;
|
||||||
|
import com.aliyuncs.green.model.v20180509.UploadCredentialsRequest;
|
||||||
|
import com.aliyuncs.http.FormatType;
|
||||||
|
import com.aliyuncs.http.HttpResponse;
|
||||||
|
import com.aliyuncs.http.ProtocolType;
|
||||||
|
import com.aliyuncs.profile.IClientProfile;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用于本地图片文件检测时,上传本地图片
|
||||||
|
*/
|
||||||
|
public class ClientUploader {
|
||||||
|
|
||||||
|
private IClientProfile profile;
|
||||||
|
private volatile UploadCredentials uploadCredentials;
|
||||||
|
private Map<String, String> headers;
|
||||||
|
private String prefix;
|
||||||
|
|
||||||
|
private boolean internal = false;
|
||||||
|
|
||||||
|
private Object lock = new Object();
|
||||||
|
|
||||||
|
private ClientUploader(IClientProfile profile, String prefix, boolean internal) {
|
||||||
|
this.profile = profile;
|
||||||
|
this.uploadCredentials = null;
|
||||||
|
this.headers = new HashMap<String, String>();
|
||||||
|
this.prefix = prefix;
|
||||||
|
this.internal = internal;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static ClientUploader getImageClientUploader(IClientProfile profile, boolean internal){
|
||||||
|
return new ClientUploader(profile, "images", internal);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ClientUploader getVideoClientUploader(IClientProfile profile, boolean internal){
|
||||||
|
return new ClientUploader(profile, "videos", internal);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ClientUploader getVoiceClientUploader(IClientProfile profile, boolean internal){
|
||||||
|
return new ClientUploader(profile, "voices", internal);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ClientUploader getFileClientUploader(IClientProfile profile, boolean internal){
|
||||||
|
return new ClientUploader(profile, "files", internal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传并获取上传后的图片链接
|
||||||
|
* @param filePath
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public String uploadFile(String filePath){
|
||||||
|
FileInputStream inputStream = null;
|
||||||
|
OSSClient ossClient = null;
|
||||||
|
try {
|
||||||
|
File file = new File(filePath);
|
||||||
|
UploadCredentials uploadCredentials = getCredentials();
|
||||||
|
if(uploadCredentials == null){
|
||||||
|
throw new RuntimeException("can not get upload credentials");
|
||||||
|
}
|
||||||
|
ObjectMetadata meta = new ObjectMetadata();
|
||||||
|
meta.setContentLength(file.length());
|
||||||
|
inputStream = new FileInputStream(file);
|
||||||
|
|
||||||
|
ossClient = new OSSClient(getOssEndpoint(uploadCredentials), uploadCredentials.getAccessKeyId(), uploadCredentials.getAccessKeySecret(), uploadCredentials.getSecurityToken());
|
||||||
|
|
||||||
|
String object = uploadCredentials.getUploadFolder() + '/' + this.prefix + '/' + String.valueOf(filePath.hashCode());
|
||||||
|
PutObjectResult ret = ossClient.putObject(uploadCredentials.getUploadBucket(), object, inputStream, meta);
|
||||||
|
return "oss://" + uploadCredentials.getUploadBucket() + "/" + object;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("upload file fail.", e);
|
||||||
|
} finally {
|
||||||
|
if(ossClient != null){
|
||||||
|
ossClient.shutdown();
|
||||||
|
}
|
||||||
|
if(inputStream != null){
|
||||||
|
try {
|
||||||
|
inputStream.close();
|
||||||
|
}catch (Exception e){
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private String getOssEndpoint(UploadCredentials uploadCredentials){
|
||||||
|
if(this.internal){
|
||||||
|
return uploadCredentials.getOssInternalEndpoint();
|
||||||
|
}else{
|
||||||
|
return uploadCredentials.getOssEndpoint();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传并获取上传后的图片链接
|
||||||
|
* @param bytes
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public String uploadBytes(byte[] bytes){
|
||||||
|
OSSClient ossClient = null;
|
||||||
|
try {
|
||||||
|
UploadCredentials uploadCredentials = getCredentials();
|
||||||
|
if(uploadCredentials == null){
|
||||||
|
throw new RuntimeException("can not get upload credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
ossClient = new OSSClient(getOssEndpoint(uploadCredentials), uploadCredentials.getAccessKeyId(), uploadCredentials.getAccessKeySecret(), uploadCredentials.getSecurityToken());
|
||||||
|
|
||||||
|
String object = uploadCredentials.getUploadFolder() + '/' + this.prefix + '/' + UUID.randomUUID().toString();
|
||||||
|
PutObjectResult ret = ossClient.putObject(uploadCredentials.getUploadBucket(), object, new ByteArrayInputStream(bytes));
|
||||||
|
return "oss://" + uploadCredentials.getUploadBucket() + "/" + object;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("upload file fail.", e);
|
||||||
|
} finally {
|
||||||
|
if(ossClient != null){
|
||||||
|
ossClient.shutdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void addHeader(String key, String value){
|
||||||
|
this.headers.put(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private UploadCredentials getCredentials() throws Exception{
|
||||||
|
if(this.uploadCredentials == null || this.uploadCredentials.getExpiredTime() < System.currentTimeMillis()){
|
||||||
|
synchronized(lock){
|
||||||
|
if(this.uploadCredentials == null || this.uploadCredentials.getExpiredTime() < System.currentTimeMillis()){
|
||||||
|
this.uploadCredentials = getCredentialsFromServer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.uploadCredentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从服务器端获取上传凭证
|
||||||
|
* @return
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
private UploadCredentials getCredentialsFromServer() throws Exception{
|
||||||
|
UploadCredentialsRequest uploadCredentialsRequest = new UploadCredentialsRequest();
|
||||||
|
uploadCredentialsRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
|
||||||
|
uploadCredentialsRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
|
||||||
|
uploadCredentialsRequest.setEncoding("utf-8");
|
||||||
|
uploadCredentialsRequest.setProtocol(ProtocolType.HTTP);
|
||||||
|
for (Map.Entry<String, String> kv : this.headers.entrySet()) {
|
||||||
|
uploadCredentialsRequest.putHeaderParameter(kv.getKey(), kv.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadCredentialsRequest.setHttpContent(new JSONObject().toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
|
||||||
|
|
||||||
|
IAcsClient client = null;
|
||||||
|
try{
|
||||||
|
client = new DefaultAcsClient(profile);
|
||||||
|
HttpResponse httpResponse = client.doAction(uploadCredentialsRequest);
|
||||||
|
if (httpResponse.isSuccess()) {
|
||||||
|
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
|
||||||
|
if (200 == scrResponse.getInteger("code")) {
|
||||||
|
JSONObject data = scrResponse.getJSONObject("data");
|
||||||
|
return new UploadCredentials(data.getString("accessKeyId"), data.getString("accessKeySecret"),
|
||||||
|
data.getString("securityToken"), data.getLongValue("expiredTime"),
|
||||||
|
data.getString("ossEndpoint"), data.getString("ossInternalEndpoint"), data.getString("uploadBucket"), data.getString("uploadFolder"));
|
||||||
|
}
|
||||||
|
|
||||||
|
String requestId = scrResponse.getString("requestId");
|
||||||
|
throw new RuntimeException("get upload credential from server fail. requestId:" + requestId + ", code:" + scrResponse.getInteger("code"));
|
||||||
|
}
|
||||||
|
throw new RuntimeException("get upload credential from server fail. http response status:" + httpResponse.getStatus());
|
||||||
|
}finally {
|
||||||
|
client.shutdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
package com.bao.dating.common.aliyun.util;
|
||||||
|
|
||||||
|
|
||||||
|
import javax.activation.MimetypesFileTypeMap;
|
||||||
|
import java.io.*;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用于自定义图库上传图片
|
||||||
|
*/
|
||||||
|
public class CustomLibUploader {
|
||||||
|
|
||||||
|
|
||||||
|
public String uploadFile(String host, String uploadFolder, String ossAccessKeyId,
|
||||||
|
String policy, String signature,
|
||||||
|
String filepath) throws Exception {
|
||||||
|
LinkedHashMap<String, String> textMap = new LinkedHashMap<String, String>();
|
||||||
|
// key
|
||||||
|
String objectName = uploadFolder + "/imglib_" + UUID.randomUUID().toString() + ".jpg";
|
||||||
|
textMap.put("key", objectName);
|
||||||
|
// Content-Disposition
|
||||||
|
textMap.put("Content-Disposition", "attachment;filename="+filepath);
|
||||||
|
// OSSAccessKeyId
|
||||||
|
textMap.put("OSSAccessKeyId", ossAccessKeyId);
|
||||||
|
// policy
|
||||||
|
textMap.put("policy", policy);
|
||||||
|
// Signature
|
||||||
|
textMap.put("Signature", signature);
|
||||||
|
|
||||||
|
Map<String, String> fileMap = new HashMap<String, String>();
|
||||||
|
fileMap.put("file", filepath);
|
||||||
|
|
||||||
|
String ret = formUpload(host, textMap, fileMap);
|
||||||
|
System.out.println("[" + host + "] post_object:" + objectName);
|
||||||
|
System.out.println("post reponse:" + ret);
|
||||||
|
return objectName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) throws Exception {
|
||||||
|
String res = "";
|
||||||
|
HttpURLConnection conn = null;
|
||||||
|
String BOUNDARY = "9431149156168";
|
||||||
|
try {
|
||||||
|
URL url = new URL(urlStr);
|
||||||
|
conn = (HttpURLConnection) url.openConnection();
|
||||||
|
conn.setConnectTimeout(5000);
|
||||||
|
conn.setReadTimeout(10000);
|
||||||
|
conn.setDoOutput(true);
|
||||||
|
conn.setDoInput(true);
|
||||||
|
conn.setRequestMethod("POST");
|
||||||
|
conn.setRequestProperty("User-Agent",
|
||||||
|
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
|
||||||
|
conn.setRequestProperty("Content-Type",
|
||||||
|
"multipart/form-data; boundary=" + BOUNDARY);
|
||||||
|
|
||||||
|
OutputStream out = new DataOutputStream(conn.getOutputStream());
|
||||||
|
// text
|
||||||
|
if (textMap != null) {
|
||||||
|
StringBuffer strBuf = new StringBuffer();
|
||||||
|
Iterator iter = textMap.entrySet().iterator();
|
||||||
|
int i = 0;
|
||||||
|
while (iter.hasNext()) {
|
||||||
|
Map.Entry entry = (Map.Entry) iter.next();
|
||||||
|
String inputName = (String) entry.getKey();
|
||||||
|
String inputValue = (String) entry.getValue();
|
||||||
|
if (inputValue == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (i == 0) {
|
||||||
|
strBuf.append("--").append(BOUNDARY).append(
|
||||||
|
"\r\n");
|
||||||
|
strBuf.append("Content-Disposition: form-data; name=\""
|
||||||
|
+ inputName + "\"\r\n\r\n");
|
||||||
|
strBuf.append(inputValue);
|
||||||
|
} else {
|
||||||
|
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
|
||||||
|
"\r\n");
|
||||||
|
strBuf.append("Content-Disposition: form-data; name=\""
|
||||||
|
+ inputName + "\"\r\n\r\n");
|
||||||
|
|
||||||
|
strBuf.append(inputValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
out.write(strBuf.toString().getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
// file
|
||||||
|
if (fileMap != null) {
|
||||||
|
Iterator iter = fileMap.entrySet().iterator();
|
||||||
|
while (iter.hasNext()) {
|
||||||
|
Map.Entry entry = (Map.Entry) iter.next();
|
||||||
|
String inputName = (String) entry.getKey();
|
||||||
|
String inputValue = (String) entry.getValue();
|
||||||
|
if (inputValue == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
File file = new File(inputValue);
|
||||||
|
String filename = file.getName();
|
||||||
|
String contentType = new MimetypesFileTypeMap().getContentType(file);
|
||||||
|
if (contentType == null || contentType.equals("")) {
|
||||||
|
contentType = "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuffer strBuf = new StringBuffer();
|
||||||
|
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
|
||||||
|
"\r\n");
|
||||||
|
strBuf.append("Content-Disposition: form-data; name=\""
|
||||||
|
+ inputName + "\"; filename=\"" + filename
|
||||||
|
+ "\"\r\n");
|
||||||
|
strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
|
||||||
|
|
||||||
|
out.write(strBuf.toString().getBytes());
|
||||||
|
|
||||||
|
DataInputStream in = new DataInputStream(new FileInputStream(file));
|
||||||
|
int bytes = 0;
|
||||||
|
byte[] bufferOut = new byte[1024];
|
||||||
|
while ((bytes = in.read(bufferOut)) != -1) {
|
||||||
|
out.write(bufferOut, 0, bytes);
|
||||||
|
}
|
||||||
|
in.close();
|
||||||
|
}
|
||||||
|
StringBuffer strBuf = new StringBuffer();
|
||||||
|
out.write(strBuf.toString().getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
|
||||||
|
out.write(endData);
|
||||||
|
out.flush();
|
||||||
|
out.close();
|
||||||
|
|
||||||
|
// 读取返回数据
|
||||||
|
StringBuffer strBuf = new StringBuffer();
|
||||||
|
BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||||
|
conn.getInputStream()));
|
||||||
|
String line = null;
|
||||||
|
while ((line = reader.readLine()) != null) {
|
||||||
|
strBuf.append(line).append("\n");
|
||||||
|
}
|
||||||
|
res = strBuf.toString();
|
||||||
|
reader.close();
|
||||||
|
reader = null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("发送POST请求出错: " + urlStr);
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
if (conn != null) {
|
||||||
|
conn.disconnect();
|
||||||
|
conn = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.bao.dating.common.aliyun.util;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class UploadCredentials implements Serializable {
|
||||||
|
|
||||||
|
private String accessKeyId;
|
||||||
|
private String accessKeySecret;
|
||||||
|
private String securityToken;
|
||||||
|
private Long expiredTime;
|
||||||
|
private String ossEndpoint;
|
||||||
|
private String ossInternalEndpoint;
|
||||||
|
private String uploadBucket;
|
||||||
|
private String uploadFolder;
|
||||||
|
|
||||||
|
public UploadCredentials(String accessKeyId, String accessKeySecret, String securityToken, Long expiredTime, String ossEndpoint, String ossInternalEndpoint, String uploadBucket, String uploadFolder) {
|
||||||
|
this.accessKeyId = accessKeyId;
|
||||||
|
this.accessKeySecret = accessKeySecret;
|
||||||
|
this.securityToken = securityToken;
|
||||||
|
this.expiredTime = expiredTime;
|
||||||
|
this.ossEndpoint = ossEndpoint;
|
||||||
|
this.ossInternalEndpoint = ossInternalEndpoint;
|
||||||
|
this.uploadBucket = uploadBucket;
|
||||||
|
this.uploadFolder = uploadFolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAccessKeyId() {
|
||||||
|
return accessKeyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAccessKeyId(String accessKeyId) {
|
||||||
|
this.accessKeyId = accessKeyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAccessKeySecret() {
|
||||||
|
return accessKeySecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAccessKeySecret(String accessKeySecret) {
|
||||||
|
this.accessKeySecret = accessKeySecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSecurityToken() {
|
||||||
|
return securityToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSecurityToken(String securityToken) {
|
||||||
|
this.securityToken = securityToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getExpiredTime() {
|
||||||
|
return expiredTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpiredTime(Long expiredTime) {
|
||||||
|
this.expiredTime = expiredTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOssEndpoint() {
|
||||||
|
return ossEndpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOssEndpoint(String ossEndpoint) {
|
||||||
|
this.ossEndpoint = ossEndpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUploadBucket() {
|
||||||
|
return uploadBucket;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUploadBucket(String uploadBucket) {
|
||||||
|
this.uploadBucket = uploadBucket;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUploadFolder() {
|
||||||
|
return uploadFolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUploadFolder(String uploadFolder) {
|
||||||
|
this.uploadFolder = uploadFolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOssInternalEndpoint() {
|
||||||
|
return ossInternalEndpoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOssInternalEndpoint(String ossInternalEndpoint) {
|
||||||
|
this.ossInternalEndpoint = ossInternalEndpoint;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,4 +22,7 @@ aliyun:
|
|||||||
endpoint: oss-cn-beijing.aliyuncs.com
|
endpoint: oss-cn-beijing.aliyuncs.com
|
||||||
access-key-id: LTAI5tKo9TpWH1aW6JxWm1Gp
|
access-key-id: LTAI5tKo9TpWH1aW6JxWm1Gp
|
||||||
access-key-secret: LHk9DdHECKCwIdaIM9fkGgEuowt18W
|
access-key-secret: LHk9DdHECKCwIdaIM9fkGgEuowt18W
|
||||||
bucket-name: heimato
|
bucket-name: heimato
|
||||||
|
accessKeyId: LTAI5t5vpcbCZwweNHEDDDaF
|
||||||
|
secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||||
|
scenes: antispam
|
||||||
|
|||||||
@@ -1,13 +1,57 @@
|
|||||||
package com.bao.dating;
|
package com.bao.dating;
|
||||||
|
|
||||||
|
import com.bao.dating.common.aliyun.GreenImageScan;
|
||||||
|
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
@SpringBootTest
|
import java.util.Arrays;
|
||||||
class DatingApplicationTests {
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@SpringBootTest // 添加这个注解以启用Spring上下文
|
||||||
|
public class DatingApplicationTests {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GreenTextScan greenTextScan;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GreenImageScan greenImageScan;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void contextLoads() {
|
public void testScanText() throws Exception {
|
||||||
|
Map map = greenTextScan.greeTextScan("冰毒");
|
||||||
|
System.out.println(map);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 测试从网络URL上传图片到阿里云OSS并进行内容安全检测
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void testUploadAndScanImageFromUrl() {
|
||||||
|
try {
|
||||||
|
// 阿里oss图片url
|
||||||
|
String imageUrl = "https://heimato.oss-cn-beijing.aliyuncs.com/9d1325d1-6e5a-426c-8081-306e7d3f6386.jpg?x-oss-credential=LTAI5tKo9TpWH1aW6JxWm1Gp%2F20251218%2Fcn-beijing%2Foss%2Faliyun_v4_request&x-oss-date=20251218T132839Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-signature=a1b6b5a8e8728012093e9c38c6fb6f4487e7adf983db63c412848d3dbb0697b8";
|
||||||
|
|
||||||
|
// 将图片URL添加到列表中进行检测
|
||||||
|
List<String> imageUrls = Arrays.asList(imageUrl);
|
||||||
|
|
||||||
|
// 调用图片检测服务
|
||||||
|
Map<String, String> scanResult = greenImageScan.imageScan(imageUrls);
|
||||||
|
|
||||||
|
if (scanResult != null) {
|
||||||
|
System.out.println("图片检测结果:");
|
||||||
|
System.out.println("建议: " + scanResult.get("suggestion"));
|
||||||
|
System.out.println("标签: " + scanResult.get("label"));
|
||||||
|
} else {
|
||||||
|
System.out.println("图片检测失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user