本示例介绍如何使用Alibaba Cloud SDK for Java提交图片异步检测任务,并查询检测结果。

背景信息

  • 图片审核支持同步检测和异步检测两种方式。同步检测实时返回检测结果;异步检测需要您轮询结果或者通过callback回调通知获取检测结果。
  • 图片支持传入互联网图片URL、本地图片文件路径以及二进制图片文件流。

前提条件

在使用本教程之前,请确保已完成以下操作:
  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见 阿里云开发工具包(SDK)
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-green -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-green</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-oss -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>
    </dependencies>
  • 如果使用本地文件或者二进制文件检测,请下载并在项目工程中引入Extension.Uploader工具类

代码示例

  • 上传图片URL进行异步检测:
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.CommonRequest;
    import com.aliyuncs.CommonResponse;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.MethodType;
    import com.aliyuncs.http.ProtocolType;
    import com.aliyuncs.profile.DefaultProfile;
    import org.apache.commons.codec.binary.StringUtils;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.UUID;
    
    public class ImageAsyncScan {
    
        public static void main(String[] args) {
            DefaultProfile profile = DefaultProfile.getProfile(
                    "<your-region-id>", // 您的可用区ID
                    "<your-access-key-id>", // 您的AccessKey ID
                    "<your-access-key-secret>"); // 您的AccessKey Secret
            IAcsClient client = new DefaultAcsClient(profile);
    
            CommonRequest request = new CommonRequest();
            // 指定请求方式
            request.setSysMethod(MethodType.POST);
            // 指定请求地址
            request.setSysDomain("green.cn-hangzhou.aliyuncs.com");
            // 指定请求方法
            request.setSysUriPattern("/green/image/asyncscan");
            // 指定请求版本
            request.setSysVersion("2018-05-09");
            // 支持HTTP和HTTPS
            request.setSysProtocol(ProtocolType.HTTPS);
    
            JSONObject httpBody = new JSONObject();
            // 设置要检测的场景, 计费是按照该处传递的场景进行
            // 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算
            // 例如:检测2张图片,场景传递porn、terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算
            // porn: porn表示色情场景检测
            httpBody.put("scenes", Arrays.asList("porn"));
    
            // 设置待检测图片, 一张图片一个task
            // 多张图片同时检测时,处理的时间由最后一个处理完的图片决定
            // 通常情况下批量检测的平均rt比单张检测的要长, 一次批量提交的图片数越多,rt被拉长的概率越高
            // 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            //设置图片链接为上传后的url
            task.put("url", "https://www.baidu.com/img/bd_logo1.png");
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            request.setHttpContent(StringUtils.getBytesUtf8(httpBody.toJSONString()),
                    "UTF-8", FormatType.JSON);
    
            // 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置
            // 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常
            request.setSysConnectTimeout(3000);
            request.setSysReadTimeout(10000);
            CommonResponse httpResponse = null;
            try {
                CommonResponse response = client.getCommonResponse(request);
                JSONObject dataJson = JSON.parseObject(response.getData());
                System.out.println(JSON.toJSONString(dataJson, true));
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                System.out.println("ErrCode:" + e.getErrCode());
                System.out.println("ErrMsg:" + e.getErrMsg());
                System.out.println("RequestId:" + e.getRequestId());
            }
        }
    }
  • 查询异步检测结果:
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.CommonRequest;
    import com.aliyuncs.CommonResponse;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.MethodType;
    import com.aliyuncs.http.ProtocolType;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.profile.IClientProfile;
    import org.apache.commons.codec.binary.StringUtils;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {
            IClientProfile profile = DefaultProfile.getProfile(
                    "<your-region-id>", // 您的可用区ID
                    "<your-access-key-id>", // 您的AccessKey ID
                    "<your-access-key-secret>"); // 您的AccessKey Secret
            IAcsClient client = new DefaultAcsClient(profile);
    
            CommonRequest request = new CommonRequest();
            // 指定请求方式
            request.setSysMethod(MethodType.POST);
            // 指定请求地址
            request.setSysDomain("green.cn-hangzhou.aliyuncs.com");
            // 指定请求方法
            request.setSysUriPattern("/green/image/results");
            // 指定请求版本
            request.setSysVersion("2018-05-09");
            // 支持HTTP和HTTPS
            request.setSysProtocol(ProtocolType.HTTPS);
    
            ArrayList<String> taskIds = new ArrayList<String>();
            // 云盾内容安全服务器返回的,唯一标识该检测任务的ID。
            taskIds.add("img1j*****7u-1rG8Ny");
            request.setHttpContent(JSON.toJSONString(taskIds).getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            /**
             * 请务必设置超时时间
             */
            request.setSysConnectTimeout(3000);
            request.setSysReadTimeout(10000);
            CommonResponse httpResponse = null;
            try {
                CommonResponse response = client.getCommonResponse(request);
                JSONObject dataJson = JSON.parseObject(response.getData());
                System.out.println(JSON.toJSONString(dataJson, true));
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                System.out.println("ErrCode:" + e.getErrCode());
                System.out.println("ErrMsg:" + e.getErrMsg());
                System.out.println("RequestId:" + e.getRequestId());
            }
        }
    }

执行结果

  • 异步检测执行结果类似如下:
    {
        "msg":"OK",
        "code":200,
        "data":[
            {
                "msg":"OK",
                "code":200,
                "dataId":"d6ab5*****f8240e9b",
                "taskId":"img1j*****7u-1rG8Ny",
                "url":"https://www.baidu.com/img/bd_logo1.png"
            }
        ],
        "requestId":"17328E39-1DA4-4C3D-B1CC-AC7C70CA9196"
    }
  • 查询检测结果正确的返回类似如下:
    {
        "msg":"OK",
        "code":200,
        "data":[
            {
                "msg":"OK",
                "code":200,
                "dataId":"71fbef66-fd5f-4b70-80fb-290783bab9ad",
                "extras":{},
                "results":[
                    {
                        "rate":99.83,
                        "suggestion":"pass",
                        "label":"normal",
                        "scene":"porn"
                    }
                ],
                "taskId":"img1j*****7u-1rG8Ny",
                "url":"https://www.baidu.com/img/bd_logo1.png"
            }
        ],
        "requestId":"52B0B37F-488E-4CE9-ABEC-3335D31E8AAA"
    }