springboot项目整合阿里云 内容审核

第一 添加依赖

<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.1.1</version>
</dependency>
<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-green</artifactId><version>3.4.1</version>
</dependency><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version>
</dependency>

第二引入工具类


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.heima.common.aliyun.utils.ClientUploader;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
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;/*** https://help.aliyun.com/document_detail/53424.html?spm=a2c4g.11186623.6.746.3aa35be6mIkNMX#section-mmy-m1w-fgb* https://help.aliyun.com/document_detail/50170.html?spm=a2c4g.11186623.6.744.12bcbb0a99YnPT* 参考阿里云文档进行优化改造* @param imageList* @return* @throws Exception*/public Map imageScan(List<byte[]> imageList) throws Exception {IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secret);DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");IAcsClient client = new DefaultAcsClient(profile);ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();// 指定api返回格式imageSyncScanRequest.setAcceptFormat(FormatType.JSON);// 指定请求方法imageSyncScanRequest.setMethod(MethodType.POST);imageSyncScanRequest.setEncoding("utf-8");//支持http和httpsimageSyncScanRequest.setProtocol(ProtocolType.HTTP);JSONObject httpBody = new JSONObject();/*** 设置要检测的场景, 计费是按照该处传递的场景进行* 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算* 例如:检测2张图片,场景传递porn、terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算* porn: porn表示色情场景检测*/httpBody.put("scenes", Arrays.asList(scenes.split(",")));/*** 如果您要检测的文件存于本地服务器上,可以通过下述代码片生成url* 再将返回的url作为图片地址传递到服务端进行检测*//*** 设置待检测图片, 一张图片一个task* 多张图片同时检测时,处理的时间由最后一个处理完的图片决定* 通常情况下批量检测的平均rt比单张检测的要长, 一次批量提交的图片数越多,rt被拉长的概率越高* 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task*/ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);String url = null;List<JSONObject> urlList = new ArrayList<JSONObject>();for (byte[] bytes : imageList) {url = clientUploader.uploadBytes(bytes);JSONObject task = new JSONObject();task.put("dataId", UUID.randomUUID().toString());//设置图片链接为上传后的urltask.put("url", url);task.put("time", new Date());urlList.add(task);}httpBody.put("tasks", urlList);imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),"UTF-8", FormatType.JSON);/*** 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置* 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常*/imageSyncScanRequest.setConnectTimeout(6000);imageSyncScanRequest.setReadTimeout(20000);HttpResponse httpResponse = null;try {httpResponse = client.doAction(imageSyncScanRequest);} catch (Exception e) {e.printStackTrace();}Map<String, String> resultMap = new HashMap<>();//服务端接收到请求,并完成处理返回的结果if (httpResponse != null && httpResponse.isSuccess()) {JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));System.out.println(JSON.toJSONString(scrResponse, true));int requestCode = scrResponse.getIntValue("code");//每一张图片的检测结果JSONArray taskResults = scrResponse.getJSONArray("data");if (200 == requestCode) {for (Object taskResult : taskResults) {//单张图片的处理结果int taskCode = ((JSONObject) taskResult).getIntValue("code");//图片要检测的场景的处理结果, 如果是多个场景,则会有每个场景的结果JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");if (200 == taskCode) {for (Object sceneResult : sceneResults) {String scene = ((JSONObject) sceneResult).getString("scene");String label = ((JSONObject) sceneResult).getString("label");String suggestion = ((JSONObject) sceneResult).getString("suggestion");//根据scene和suggetion做相关处理//do somethingSystem.out.println("scene = [" + scene + "]");System.out.println("suggestion = [" + suggestion + "]");System.out.println("suggestion = [" + label + "]");if (!suggestion.equals("pass")) {resultMap.put("suggestion", suggestion);resultMap.put("label", label);return resultMap;}}} else {//单张图片处理失败, 原因视具体的情况详细分析System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));return null;}}resultMap.put("suggestion","pass");return resultMap;} else {/*** 表明请求整体处理失败,原因视具体的情况详细分析*/System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));return null;}}return null;}}

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;import java.util.*;@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun")
public class GreenTextScan {private String accessKeyId;private String secret;//可以进行优化 优化成 数组或者是List集合 因为一次性可以执行不超过100个任务// https://www.aliyun.com/price/product?spm=5176.55804.J_911092.btn4.3d9875daIbvZvU#/lvwang/detail/*** 基本描述:根据您调用API的文本扫描条数计费。影响扫描费用的因素如下:* 1. 2017年8月1日起正式商业化;* 2. 一次请求最多支持100个任务,一个任务就是算一条文本,每条文本限制10,000个字符,超出限制该请求所有任务全部失败,不计费。当前的计费周期为1天1次;* 3. 每名用户从开始调用之日起算(包含当天),31天内拥有每日3,000条免费文本扫描额度,不区分算法结果是否确定,第32天开始将不再享有免费量;* 4. 31天内每日超出3,000条的部分需要付费,价格按照当日总扫描量匹配阶梯价收费,每日扫描量越大,单价越低。* 5.计费项code :text_scan** @param contents* @return* @throws Exception*/public Map greeTextScan(List<String> contents) throws Exception {IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secret);DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");IAcsClient client = new DefaultAcsClient(profile);TextScanRequest textScanRequest = new TextScanRequest();textScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式textScanRequest.setHttpContentType(FormatType.JSON);textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法textScanRequest.setEncoding("UTF-8");textScanRequest.setRegionId("cn-shanghai");List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();for (String content : contents) {Map<String, Object> task1 = new LinkedHashMap<String, Object>();task1.put("dataId", UUID.randomUUID().toString());/*** 待检测的文本,长度不超过10000个字符*/task1.put("content", content);tasks.add(task1);}JSONObject data = new JSONObject();/*** 检测场景,文本垃圾检测传递:antispam**/data.put("scenes", Arrays.asList("antispam"));data.put("tasks", tasks);System.out.println(JSON.toJSONString(data, true));textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);// 请务必设置超时时间textScanRequest.setConnectTimeout(6000);textScanRequest.setReadTimeout(12000);Map<String, String> resultMap = new HashMap<>();try {HttpResponse httpResponse = client.doAction(textScanRequest);if (httpResponse.isSuccess()) {JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));System.out.println(JSON.toJSONString(scrResponse, true));if (200 == scrResponse.getInteger("code")) {JSONArray taskResults = scrResponse.getJSONArray("data");for (Object taskResult : taskResults) {if (200 == ((JSONObject) taskResult).getInteger("code")) {JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");for (Object sceneResult : sceneResults) {String scene = ((JSONObject) sceneResult).getString("scene");String label = ((JSONObject) sceneResult).getString("label");String suggestion = ((JSONObject) sceneResult).getString("suggestion");System.out.println("suggestion = [" + label + "]");if (!suggestion.equals("pass")) {resultMap.put("suggestion", suggestion);resultMap.put("label", label);return resultMap;}}} else {return null;}}resultMap.put("suggestion", "pass");return resultMap;} else {return null;}} else {return null;}} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return null;}public static void main(String[] args) throws Exception {//请替换成你自己的accessKeyId、accessKeySecretIClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI4G7MDn5xd9nbkZz5Co9P", "7mTndVHmvLTwQjG4OieS9KmufYyhaD");DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");IAcsClient client = new DefaultAcsClient(profile);TextScanRequest textScanRequest = new TextScanRequest();textScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法textScanRequest.setEncoding("UTF-8");textScanRequest.setRegionId("cn-shanghai");List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();Map<String, Object> task1 = new LinkedHashMap<String, Object>();task1.put("dataId", UUID.randomUUID().toString());task1.put("content", "本校小额贷款,安全、快捷、方便、无抵押,随机随贷,当天放款,上门服务。蒙汗药。联系q 946932");tasks.add(task1);/* Map<String, Object> task2 = new LinkedHashMap<String, Object>();task2.put("dataId", UUID.randomUUID().toString());task2.put("content", "蒙汗药");tasks.add(task2);Map<String, Object> task3 = new LinkedHashMap<String, Object>();task3.put("dataId", UUID.randomUUID().toString());task3.put("content", "正常人");tasks.add(task3);*/JSONObject data = new JSONObject();data.put("scenes", Arrays.asList("antispam"));data.put("tasks", tasks);textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);/*** 请务必设置超时时间*/textScanRequest.setConnectTimeout(3000);textScanRequest.setReadTimeout(6000);try {HttpResponse httpResponse = client.doAction(textScanRequest);if(httpResponse.isSuccess()){JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));System.out.println(JSON.toJSONString(scrResponse, true));if (200 == scrResponse.getInteger("code")) {JSONArray taskResults = scrResponse.getJSONArray("data");for (Object taskResult : taskResults) {if(200 == ((JSONObject)taskResult).getInteger("code")){JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");for (Object sceneResult : sceneResults) {String scene = ((JSONObject)sceneResult).getString("scene");String suggestion = ((JSONObject)sceneResult).getString("suggestion");//根据scene和suggetion做相关的处理//do somethingSystem.out.println("args = [" + scene + "]");System.out.println("args = [" + suggestion + "]");}}else{System.out.println("task process fail:" + ((JSONObject)taskResult).getInteger("code"));}}} else {System.out.println("detect not success. code:" + scrResponse.getInteger("code"));}}else{System.out.println("response not success. status:" + httpResponse.getStatus());}} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();} catch (Exception e){e.printStackTrace();}}}

添加字节流图片需要的工具类


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();}}}

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>();// keyString objectName = uploadFolder + "/imglib_" + UUID.randomUUID().toString() + ".jpg";textMap.put("key", objectName);// Content-DispositiontextMap.put("Content-Disposition", "attachment;filename="+filepath);// OSSAccessKeyIdtextMap.put("OSSAccessKeyId", ossAccessKeyId);// policytextMap.put("policy", policy);// SignaturetextMap.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());// textif (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());}// fileif (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;}}

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>();// keyString objectName = uploadFolder + "/imglib_" + UUID.randomUUID().toString() + ".jpg";textMap.put("key", objectName);// Content-DispositiontextMap.put("Content-Disposition", "attachment;filename="+filepath);// OSSAccessKeyIdtextMap.put("OSSAccessKeyId", ossAccessKeyId);// policytextMap.put("policy", policy);// SignaturetextMap.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());// textif (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());}// fileif (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;}}

添加yml文件配置

aliyun:accessKeyId: LTA******y1WmfFBsecret: Crha1kk******X2GiJvK9tUJ6
#aliyun.scenes=porn,terrorism,ad,qrcode,live,logoscenes: porn,terrorism,ad,qrcode,live,logo

测试


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.ArrayList;
import java.util.List;
import java.util.Map;@RunWith(SpringRunner.class)
@SpringBootTest(classes = WemediaApplication.class)
public class AliyunTest {@Autowiredprivate GreenTextScan greenTextScan;@Autowiredprivate GreenImageScan greenImageScan;@Autowiredprivate MinIOFileStorageService storageService;@Testpublic void testScanText() throws Exception {List<String> list = new ArrayList<>();list.add("小明");list.add("如花");list.add("冰毒");Map result = greenTextScan.greeTextScan(list);System.out.println("检测结果:"+result);}@Testpublic void testScanImage() throws Exception {List<byte[]> list = new ArrayList<>();//从MinIO下载一张图片byte[] image = storageService.downLoadFile("http://192.168.66.133:9000/leadnews/2022/01/19/9f63cc24d6c64ab98f49469a0f150d55.jpeg");list.add(image);Map result = greenImageScan.imageScan(list);System.out.println("检测结果:"+result);}
}

springboot项目整合阿里云oss的内容审核相关推荐

  1. 在线教育_Day06_项目整合阿里云OSS和Excel导入分类

    一.阿里云OSS概述及开通 1.1 对象存储OSS 为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS. 1.2 开通"对象存储OSS"服务 (1)申请 ...

  2. java的springboot项目操作阿里云OSS下载文件、查看文件内容、上传文件,自定义工具类

    因为要从oss下载.查看.上传工具类,所以对这几个方法做了一个封装,已经经过测试,可以直接使用 1.yml添加上阿里云配置.添加maven配置 注意这里的objectName: xxx/xxx/,前面 ...

  3. SpringBoot整合阿里云OSS文件上传、下载、查看、删除

    SpringBoot整合阿里云OSS文件上传.下载.查看.删除 该项目源码地址:https://github.com/ggb2312/springboot-integration-examples ( ...

  4. SpringBoot整合阿里云OSS

    文章目录 SpringBoot整合阿里云OSS 1.准备工作 1.1 开通"对象存储OSS"服务 1.2 创建Bucket 1.3 创建RAM子用户 2.SpringBoot整合阿 ...

  5. springboot整合阿里云oss上传的方法示例

    这篇文章主要介绍了springboot整合阿里云oss上传的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 OSS申请和 ...

  6. ThinkPHP5整合阿里云oss

    [分享]ThinkPHP5整合阿里云oss 浏览:11716 发布日期:2016/12/24 分类:ThinkPHP5专区 关键字: thinkphp5 OSS 整合 社区推荐: 阿里云3月采购季活动 ...

  7. spring boot 整合 阿里云oss上传

    Spring Boot 整合 阿里云OSS上传 OSS申请和配置 1. 注册登录 2.开通以及配置 springboot整合使用 1. 进入我们springboot的项目中,导入oss相关依赖 2. ...

  8. 【谷粒商城之整合阿里云OSS对象存储】

    本笔记内容为尚硅谷谷粒商城整合阿里云OSS对象存储部分 目录 一 .简介 二.云存储开通与使用 1.开通阿里云对象存储服务 2.创建bucket 3.创建子用户(获取密钥访问OSS服务器) 给该子账户 ...

  9. java整合阿里云OSS

    java整合阿里云OSS 说明 一.OSS前期准备 (1)创建Bucket (2)创建RAM账号 创建用户 创建用户组 二.OSS对应API开发(java) 说明 更新时间:2021/1/7 16:3 ...

最新文章

  1. 20个经典要诀学好英语
  2. win10 IIS(互联网信息服务) 及 外网访问tomcat
  3. C语言定义了一个结构体怎么分配内存?C\C++中结构体变量与结构体指针内存分配问题?
  4. Sklearn(v3)——朴素贝叶斯(1)
  5. Css 特殊或不常用属性
  6. MySQL 5.7.10 免安装配置
  7. 【Linux网络编程学习】阻塞、非阻塞、同步、异步以及五种I/O模型
  8. 关于神经网络权重初始值的设置的研究
  9. 云原生应用程序_什么是云原生应用程序?
  10. 郎朗钢琴课独家上线知乎 手把手带你开启钢琴之路
  11. OO第一单元总结分析
  12. java堆栈_Java堆栈– Java堆栈
  13. python print_Python print()
  14. js实现签名功能(vue中使用电子签名)
  15. python成绩统计_巧用python对学生成绩计算总分并排序
  16. 什么是 Docker ?
  17. android ios相机,曝苹果iOS13相机加入了这项功能 安卓上早就有了
  18. 打开Word提示向程序发送命令时出现问题怎么办
  19. Sexagenary Cycle(干支纪年)
  20. Android平台下JNI调用第三方so库

热门文章

  1. 用数组存储三个学生对象,并遍历数组
  2. VB制作网页自动填表(强烈推荐)
  3. 全球最强截图软件 Snipaste
  4. 最新巨作!阿布扎比文化和旅游部官宣建一座全球博物馆,2025年完工
  5. 2023最新整理,Android车载操作系统开发揭秘,无偿分享!
  6. 【GIS前沿】科学家绘制全球140多万个湖泊和水库的水下地形图
  7. 解决org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 异常
  8. 推荐《怪诞行为学:可预测的非理性》
  9. P1111 修复公路P1195 口袋的天空
  10. 智能运维案例系列 | 新网银行 X 袋鼠云:银行核心业务系统日志监控平台建设实践...