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

Background information

Content Moderation SDK for Java supports both synchronous and asynchronous image moderation.
Moderation method Moderation object Method for obtaining moderation results
Recommended: Submit synchronous image moderation tasks.

ImageSyncScanRequest

You can submit the URL of an online image, the URL of a local image, or a binary image stream for image moderation. You can obtain moderation results in real time.
Submit asynchronous image moderation tasks.

ImageAsyncScanRequest

You can submit the URL of an online image, the URL of a local image, or a binary image stream for image moderation. You can use one of the following methods to obtain moderation results:
  • When you submit asynchronous image moderation tasks, specify the callback URL by setting the callback parameter. After the tasks are processed, Content Moderation sends the moderation results to the specified callback URL.
  • After you submit asynchronous image moderation tasks, you can call the ImageAsyncScanResultsRequest operation to poll the moderation results.

Before you begin

Before you call operations, make the following preparations:

Recommended: Submit synchronous image moderation tasks

Operation Description Supported region
ImageSyncScanRequest Sends synchronous requests to moderate images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
  • us-west-1: US (Silicon Valley)
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 separately calculated 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, a value of porn indicates that the server detects pornography.
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * Create a 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.
             * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a 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);
    
            /**
             * Specify the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10s.
             * If you set the read timeout to a period shorter than 10s, the server is prone to generate a read timeout error during request processing.
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results that are 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 results of each image.
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation results of a single image.
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is 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 separately calculated 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, a value of porn indicates that the server detects pornography.
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * If you want to moderate a local image, use the following code snippet to generate a URL based on the storage path of the image.
             * Then, submit the generated URL of the image 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 a 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.
             * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a 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 that is 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);
    
            /**
             * Specify the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10s.
             * If you set the read timeout to a period shorter than 10s, the server is prone to generate a read timeout error during request processing.
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results that are 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 results of each image.
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation results of a single image.
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is 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 separately calculated 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, a value of porn indicates that the server detects pornography.
             */
            httpBody.put("scenes", Arrays.asList("porn"));
    
            /**
             * If you want to moderate a local image, use the following code snippet to generate a URL based on the storage path of the image.
             * Then, submit the generated URL of the image to the server.
             */
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            byte[] imageBytes = null;
            String url = null;
            try{
                // Read and convert a local image to binary data and submit the binary data for moderation. In the actual code, directly use the binary data of your image.
                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 a 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.
             * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a 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 that is 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);
    
            /**
             * Specify the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10s.
             * If you set the read timeout to a period shorter than 10s, the server is prone to generate a read timeout error during request processing.
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
            HttpResponse httpResponse = null;
            try {
                httpResponse = client.doAction(imageSyncScanRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // The results that are 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 results of each image.
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation results of a single image.
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is 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

This section describes how to use Content Moderation SDK for Java to call the ImageAsyncScanRequest operation and moderate images for risky content. You can send an asynchronous request to submit image moderation tasks. When you submit the request, you can specify the callback URL to receive moderation results by setting the callback parameter. Alternatively, you can call the ImageAsyncScanResultsRequest operation to poll the moderation results after Content Moderation processes the image moderation tasks.

Same as 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. In this example, the URL of an online image is used.

Operation Description Supported region
ImageAsyncScanRequest Sends asynchronous requests to moderate 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.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
  • us-west-1: US (Silicon Valley)
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 separately calculated 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, a value of 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 a task for each image to be moderated. You can moderate a maximum of 50 images at a time. In this case, you must 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.
         * In this example, a single image is to be moderated. If you want to moderate multiple images at a time, create a 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);

        /**
         * Specify the connection timeout and read timeout. The timeout period for the server to complete an image moderation request is 10s.
         * If you set the read timeout to a period shorter than 10s, the server is prone to generate a read timeout error during request processing.
         */
        imageAsyncScanRequest.setConnectTimeout(3000);
        imageAsyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageAsyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // The results that are 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 results of each image.
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // The moderation results of a single image.
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned.
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        // Save the task ID, which is used to poll the moderation results.
                        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));
            }
        }
    }
}

Obtain asynchronous image moderation results

Operation Description Supported region
ImageAsyncScanResultsRequest Queries asynchronous image moderation results. You can query the moderation results of multiple asynchronous image moderation tasks at a time.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
  • us-west-1: US (Silicon Valley)
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);

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