Text anti-spam
Use AI Guardrails SDK for Java to scan text for spam, including pornographic and terrorist content. Only synchronous moderation is supported.
Billing is based on the number of text entries submitted per request. For details, see Billing overview.
Prerequisites
Before you begin, ensure that you have:
Java dependencies installed using the version specified in Installation. Using a different Java version causes operation calls to fail.
(Optional) Extension.Uploader utility class downloaded and imported into your project, if you plan to submit local images or binary image streams for image moderation.
Scan text for spam
TextScanRequest submits synchronous text moderation tasks with scenes set to antispam. The following regions are supported: cn-shanghai, cn-beijing, cn-shenzhen, and ap-southeast-1.
To add custom terms (such as competitor brand names) to the block list, use the Alibaba Cloud AI Guardrails console or call an API operation. When moderated text matches a custom term, the suggestion field in the response is block.
For a full list of request and response parameters, see /green/text/scan.
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.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws Exception {
// Use a RAM user's AccessKey credentials from environment variables.
// Avoid using an Alibaba Cloud account's AccessKey directly — it has full permissions and poses a security risk.
DefaultProfile profile = DefaultProfile.getProfile(
"cn-shanghai",
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
// Reuse the client across requests to improve performance and reduce connection overhead.
IAcsClient client = new DefaultAcsClient(profile);
TextScanRequest textScanRequest = new TextScanRequest();
textScanRequest.setAcceptFormat(FormatType.JSON);
textScanRequest.setHttpContentType(FormatType.JSON);
textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST);
textScanRequest.setEncoding("UTF-8");
textScanRequest.setRegionId("cn-shanghai");
// Build the list of text entries to moderate. Each entry can contain up to 10,000 characters.
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", "test content");
tasks.add(task1);
JSONObject data = new JSONObject();
data.put("scenes", Arrays.asList("antispam")); // Set to antispam for text anti-spam moderation.
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()) {
System.out.println("response not success. status:" + httpResponse.getStatus());
return;
}
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
if (200 != scrResponse.getInteger("code")) {
System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
return;
}
JSONArray taskResults = scrResponse.getJSONArray("data");
for (Object taskResult : taskResults) {
if (200 != ((JSONObject) taskResult).getInteger("code")) {
System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
continue;
}
JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
for (Object sceneResult : sceneResults) {
String scene = ((JSONObject) sceneResult).getString("scene");
String suggestion = ((JSONObject) sceneResult).getString("suggestion");
// suggestion=pass: no spam detected.
// suggestion=block: spam detected. Check the label field for the spam category.
System.out.println("scene: " + scene);
System.out.println("suggestion: " + suggestion);
}
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}Expected output:
scene: antispam
suggestion: passKey response fields:
| Field | Type | Description |
|---|---|---|
suggestion | String | Moderation recommendation: pass (no spam detected) or block (spam detected) |
label | String | Spam category when suggestion is block (for example, spam, pornographic, terrorism) |
scene | String | The moderation scene. Returns antispam for text anti-spam tasks |
Submit feedback on moderation results
If a moderation result doesn't match your expectation, use TextFeedbackRequest to correct it. The following regions are supported: cn-shanghai, cn-beijing, cn-shenzhen, and ap-southeast-1.
After you submit feedback, the server updates the text pattern blacklist or whitelist. Subsequent requests that match the same text pattern return the label value you specified in the feedback.
For parameter details, see /green/text/feedback.
import com.alibaba.fastjson.JSON;
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.TextFeedbackRequest;
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;
public class TextFeedbackSample {
public static void main(String[] args) throws Exception {
// Use a RAM user's AccessKey credentials from environment variables.
DefaultProfile profile = DefaultProfile.getProfile(
"cn-shanghai",
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
// Reuse the client across requests to improve performance and reduce connection overhead.
IAcsClient client = new DefaultAcsClient(profile);
TextFeedbackRequest textFeedbackRequest = new TextFeedbackRequest();
textFeedbackRequest.setAcceptFormat(FormatType.JSON);
textFeedbackRequest.setMethod(MethodType.POST);
textFeedbackRequest.setEncoding("utf-8");
textFeedbackRequest.setProtocol(ProtocolType.HTTP);
// Specify the expected moderation result for the submitted text.
JSONObject httpBody = new JSONObject();
httpBody.put("dataId", "ID of the moderated text");
httpBody.put("taskId", "ID of the text moderation task");
httpBody.put("content", "Text content");
httpBody.put("label", "spam"); // The expected label for this text.
httpBody.put("note", "Remarks");
textFeedbackRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
"UTF-8", FormatType.JSON);
textFeedbackRequest.setConnectTimeout(3000);
textFeedbackRequest.setReadTimeout(10000);
try {
HttpResponse httpResponse = client.doAction(textFeedbackRequest);
if (!httpResponse.isSuccess()) {
System.out.println("response not success. status:" + httpResponse.getStatus());
return;
}
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
int requestCode = scrResponse.getIntValue("code");
if (200 != requestCode) {
System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
return;
}
System.out.println(JSON.toJSONString(scrResponse, true));
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}Feedback request fields:
| Field | Required | Description |
|---|---|---|
dataId | Yes | ID of the moderated text entry |
taskId | Yes | ID of the text moderation task returned in the scan response |
content | Yes | The text content that received an incorrect moderation result |
label | Yes | The expected spam category (for example, spam, pornographic, normal) |
note | No | Remarks about this feedback |
Integration notes
Credentials and security
Store AccessKey credentials in environment variables rather than hardcoding them. Use a RAM user's AccessKey instead of an Alibaba Cloud account's AccessKey — the account key has full permissions and poses a security risk.
Client reuse
Reuse the IAcsClient instance across requests. Creating a new client per request increases latency and connection overhead.
Batch requests
Submit multiple text entries in a single TextScanRequest. Billing applies per text entry moderated.
Timeouts
Default timeout values in the sample code:
| Setting | Value | Notes |
|---|---|---|
connectTimeout | 3,000 ms | Connection establishment timeout |
readTimeout (scan) | 6,000 ms | Response read timeout for TextScanRequest |
readTimeout (feedback) | 10,000 ms | Response read timeout for TextFeedbackRequest |
What's next
Installation — Set up the AI Guardrails SDK for Java
/green/text/scan API reference — Full parameter reference for synchronous text moderation
Billing overview — Understand how text moderation requests are charged