This topic describes how to use the Java SDK to moderate text for spam such as pornography and terrorist content.

Note Currently, the Java SDK only supports synchronous text moderation. You can send a request to moderate one or more pieces of text. The system charges you based on the number of pieces of text moderated. For more information, see Billing methods.

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.

Moderate text for spam

Text anti-spam allows you to add custom terms, such as brand terms of competitors. If the text being moderated contains the terms you add, the value of the suggestion parameter returned by the text anti-spam algorithm is block.

You can log on to the Alibaba Cloud Content Moderation console or call the corresponding operation to add terms. The terms are UTF-8-encoded. For more information about the text anti-spam operation, see Moderate text for spam.

Operation Feature Region Description
TextScanRequest Scans text for spam.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation scans text for spam after you specify antispam in the scenes parameter.
Sample code
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
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 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);
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation.
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method.
        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());
        /**
         * Enter the text to be moderated. The text can be up to 10,000 characters in length.
         */
        task1.put("content", "test content");
        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * Set the scenes parameter to 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);
        // You must set the connection timeout and read timeout.
        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");
                                // Take a further action on the text based on the values of the scene and suggestion parameters.
                                // If the value of the suggestion parameter is pass, no spam is detected. If the value of the suggestion parameter is block, spam is detected. In this case, check the value of the label parameter to obtain the spam category.
                                System.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();
        }
    }

}

Provide feedback on the text anti-spam result

If the text anti-spam result does not meet your expectations, you can call the TextFeedbackRequest operation to provide feedback on the text anti-spam result. In the feedback, you can pass a correct label for the text moderated.

The server corrects the text anti-spam result based on your feedback and adds the feedback to a text pattern blacklist or whitelist. When you submit a text pattern next time, the server returns the text anti-spam result based on the label that you passed by calling the TextFeedbackRequest operation. For more information about the feedback operation, see Give feedback on moderation results.

Operation Feature Region Description
TextFeedbackRequest Allows you to provide feedback on the text anti-spam result.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation uses the feedback provided by you to correct the text anti-spam result generated by the text anti-spam algorithm.
Sample code
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.TextFeedbackRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

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);
        TextFeedbackRequest textFeedbackRequest = new TextFeedbackRequest();
        textFeedbackRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation.
        textFeedbackRequest.setHttpContentType(FormatType.JSON);
        textFeedbackRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method.
        textFeedbackRequest.setEncoding("UTF-8");
        textFeedbackRequest.setRegionId("cn-shanghai");

        JSONObject data = new JSONObject();
        data.put("taskId", "txt6z3Na17XbrD4P7QdJzYbk1-1q4seJ");
        data.put("label", "spam");
        System.out.println(JSON.toJSONString(data, true));
        textFeedbackRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        // You must set the connection timeout and read timeout.
        textFeedbackRequest.setConnectTimeout(3000);
        textFeedbackRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(textFeedbackRequest);
            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
            }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();
        }
    }

}