This topic describes how to use the Java SDK to moderate images for risky content.

  • The Java SDK supports both synchronous and asynchronous image moderation. If you use synchronous image moderation, the moderation results are returned in real time. If you use asynchronous image moderation, you must poll the moderation results or configure a callback notification to receive the moderation results.
  • You can submit the URL of an online image, the URL of a local image, or a binary image stream for image moderation.
Note For more information about the scenarios of image moderation, see Moderate images synchronously.

Preparations

Before calling operations, make the following preparations:
  1. Create an AccessKey ID and AccessKey secret of your Alibaba Cloud account. For more information, see Create an AccessKey.
  2. Install Java dependencies. For more information, see Installation.
  3. Download and import the Extension.Uploader utility class into your project if you submit a local image or a binary image stream for image moderation.

(Recommended) Submit synchronous image moderation tasks

Operation description
Operation Feature Region Description
ImageSyncScanRequest Sends synchronous requests to moderate images for risky content.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation moderates images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.
Sample code
  • Submit the URL of an online image for image moderation
    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 java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "Your AccessKey ID", "Your AccessKey secret");
            DefaultProfile
                .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // Specify the response format of the operation.
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // Specify the request method.
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // Both HTTP and HTTPS are supported.
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify.
             * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are calculated separately and summed up.
             * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
             * In the scenes parameter, porn indicates that the server detects pornography.
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * Create one task for each image to be moderated.
             * If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
             * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
             * The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // Specify the image URL.
            task.put("url", "http://xxx.test.jpg");
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
    
            /**
             * You must set the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10 seconds.
             * If you set the read timeout to a value smaller than 10 seconds, a read timeout error is returned.
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results returned after the server receives and processes your request.
            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");
                // The moderation result of each image.
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single image.
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you have specified multiple moderation scenarios, the moderation results of the image in each scenario are returned.
                        JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                        if (200 == taskCode) {
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // Take a further action on the image based on the values of the scene and suggestion parameters.
                                // do something
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // A single image failed to be moderated. Analyze the failure based on the actual situation.
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * Your whole request failed to be processed. Analyze the failure based on the actual situation.
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }
  • Submit the URL of a local image for image moderation
    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.extension.uploader.ClientUploader;
    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 java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "Your AccessKey ID", "Your AccessKey secret");
            DefaultProfile
                .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // Specify the response format of the operation.
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // Specify the request method.
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // Both HTTP and HTTPS are supported.
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify.
             * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are calculated separately and summed up.
             * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
             * In the scenes parameter, porn indicates that the server detects pornography.
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * If you want to moderate an image stored on the local server, use the following code snippet to generate a URL based on the storage path of the image.
             * Then, submit the URL as the image address to the server.
             */
            String url = null;
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            try{
                url = clientUploader.uploadFile("d:/test.jpg");
            }catch (Exception e){
                e.printStackTrace();
            }
    
            /**
             * Create one task for each image to be moderated.
             * If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
             * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
             * The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // Set the url parameter to the image URL submitted to the server.
            task.put("url", url);
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
    
            /**
             * You must set the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10 seconds.
             * If you set the read timeout to a value smaller than 10 seconds, a read timeout error is returned.
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results returned after the server receives and processes your request.
            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");
                // The moderation result of each image.
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single image.
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you have specified multiple moderation scenarios, the moderation results of the image in each scenario are returned.
                        JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                        if (200 == taskCode) {
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // Take a further action on the image based on the values of the scene and suggestion parameters.
                                // do something
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // A single image failed to be moderated. Analyze the failure based on the actual situation.
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * Your whole request failed to be processed. Analyze the failure based on the actual situation.
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }
  • Submit a binary image stream for image moderation
    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.extension.uploader.ClientUploader;
    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 org.apache.commons.io.FileUtils;
    
    import java.io.File;
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "Your AccessKey ID", "Your AccessKey secret");
            DefaultProfile
                .addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            IAcsClient client = new DefaultAcsClient(profile);
    
            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            // Specify the response format of the operation.
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
            // Specify the request method.
            imageSyncScanRequest.setMethod(MethodType.POST);
            imageSyncScanRequest.setEncoding("utf-8");
            // Both HTTP and HTTPS are supported.
            imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
    
    
            JSONObject httpBody = new JSONObject();
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify.
             * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are calculated separately and summed up.
             * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
             * In the scenes parameter, porn indicates that the server detects pornography.
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * If you want to moderate an image stored on the local server, use the following code snippet to generate a URL based on the storage path of the image.
             * Then, submit the URL as the image address to the server.
             */
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            byte[] imageBytes = null;
            String url = null;
            try{
                // Read and convert a local video to binary data and submit the binary data for moderation. In the actual code, directly use the binary data of your video.
                imageBytes = FileUtils.readFileToByteArray(new File("/Users/01fb4ab6420b5f34623e13b82b51ef87.jpg"));
                // Upload the binary stream to the server.
                url = clientUploader.uploadBytes(imageBytes);
            }catch (Exception e){
                e.printStackTrace();
            }
    
            /**
             * Create one task for each image to be moderated.
             * If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
             * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
             * The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
             */
            JSONObject task = new JSONObject();
            task.put("dataId", UUID.randomUUID().toString());
    
            // Set the url parameter to the image URL submitted to the server.
            task.put("url", url);
            task.put("time", new Date());
            httpBody.put("tasks", Arrays.asList(task));
    
            imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);
    
            /**
             * You must set the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10 seconds.
             * If you set the read timeout to a value smaller than 10 seconds, a read timeout error is returned.
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results returned after the server receives and processes your request.
            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");
                // The moderation result of each image.
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single image.
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you have specified multiple moderation scenarios, the moderation results of the image in each scenario are returned.
                        JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                        if (200 == taskCode) {
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                // Take a further action on the image based on the values of the scene and suggestion parameters.
                                // do something
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                            }
                        } else {
                            // A single image failed to be moderated. Analyze the failure based on the actual situation.
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * Your whole request failed to be processed. Analyze the failure based on the actual situation.
                     */
                    System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            }
        }
    
    }

Submit asynchronous image moderation tasks

The following section describes how to use the ImageAsyncScanRequest operation of the Java SDK to moderate images for risky content. You can send an asynchronous request to submit an image moderation task. When submitting the request, you can configure a callback notification to receive the moderation results. Alternatively, you can call the ImageAsyncScanResultsRequest operation to poll the moderation results.

As with synchronous image moderation, you can submit the URL of an online image, the URL of a local image, or a binary image stream for asynchronous image moderation. The following sample code uses the URL of an online image as an example.

Operation description
Operation Feature Region Description
ImageAsyncScanRequest Sends asynchronous requests to moderate images for risky content.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation moderates images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.
Note You can call the ImageAsyncScanResultsRequest operation to poll the moderation results.
Sample code
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.ImageAsyncScanRequest;
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 java.util.Arrays;
import java.util.Date;
import java.util.UUID;

public class Main {

    public static void main(String[] args) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "Your AccessKey ID", "Your AccessKey secret");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        ImageAsyncScanRequest imageAsyncScanRequest = new ImageAsyncScanRequest();
        // Specify the response format of the operation.
        imageAsyncScanRequest.setAcceptFormat(FormatType.JSON);
        // Specify the request method.
        imageAsyncScanRequest.setMethod(MethodType.POST);
        imageAsyncScanRequest.setEncoding("utf-8");
        // Both HTTP and HTTPS are supported.
        imageAsyncScanRequest.setProtocol(ProtocolType.HTTP);


        JSONObject httpBody = new JSONObject();
        /**
         * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify.
         * You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are calculated separately and summed up.
         * For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
         * In the scenes parameter, porn indicates that the server detects pornography.
         */
        httpBody.put("scenes", Arrays.asList("porn"));
        httpBody.put("callback", "http://xxx.xxx.xx/xxx.json");
        httpBody.put("seed", "yourPersonalSeed");

        /**
         * Create one task for each image to be moderated. You can moderate a maximum of 50 images at a time. In this case, you need to create 50 tasks.
         * If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
         * Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
         * The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
         */
        JSONObject task = new JSONObject();
        task.put("dataId", UUID.randomUUID().toString());

        // Specify the image URL.
        task.put("url", "http://xxx.test.jpg");
        task.put("time", new Date());
        httpBody.put("tasks", Arrays.asList(task));

        imageAsyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
            "UTF-8", FormatType.JSON);

        /**
         * You must set the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10 seconds.
         * If you set the read timeout to a value smaller than 10 seconds, a read timeout error is returned.
         */
        imageAsyncScanRequest.setConnectTimeout(3000);
        imageAsyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageAsyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // The results returned after the server receives and processes your request.
        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");
            // The moderation result of each image.
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // The moderation result of a single image.
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // The moderation result of the image in a moderation scenario. If you have specified multiple moderation scenarios, the moderation results of the image in each scenario are returned.
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        // Save the task ID, which is used to poll the moderation results at the specified interval.
                        System.out.println(((JSONObject)taskResult).getString("taskId"));
                    } else {
                        // A single image failed to be moderated. Analyze the failure based on the actual situation.
                        System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                /**
                 * Your whole request failed to be processed. Analyze the failure based on the actual situation.
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
    }
}

Query the results of asynchronous image moderation

Operation description
Operation Feature Region Description
ImageAsyncScanResultsRequest Queries the results of asynchronous image moderation tasks.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation can query the moderation results of multiple asynchronous image moderation tasks at a time.
Sample code
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.ImageAsyncScanRequest;
import com.aliyuncs.green.model.v20180509.ImageAsyncScanResultsRequest;
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 java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "Your AccessKey ID", "Your AccessKey secret");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        ImageAsyncScanResultsRequest imageAsyncScanResultsRequest = new ImageAsyncScanResultsRequest();
        // Specify the response format of the operation.
        imageAsyncScanResultsRequest.setAcceptFormat(FormatType.JSON);
        // Specify the request method.
        imageAsyncScanResultsRequest.setMethod(MethodType.POST);
        imageAsyncScanResultsRequest.setEncoding("utf-8");
        // Both HTTP and HTTPS are supported.
        imageAsyncScanResultsRequest.setProtocol(ProtocolType.HTTP);


        List<String> taskIds = new ArrayList<String>();
        taskIds.add("img4hDosCHcrFk5jAMR80XWJN-1pZ@0p");
        imageAsyncScanResultsRequest.setHttpContent(JSON.toJSONString(taskIds).getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * You must set the connection timeout and read timeout.
         */
        imageAsyncScanResultsRequest.setConnectTimeout(3000);
        imageAsyncScanResultsRequest.setReadTimeout(6000);

        try {
            HttpResponse httpResponse = client.doAction(imageAsyncScanResultsRequest);

            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");
                                // Take a further action on the image based on the values of the scene and suggestion parameters.
                                // do something
                            }
                        }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();
        }
    }
}