Panduan ini memandu Anda melalui aktivasi Image Moderation 2.0, penyiapan kredensial, serta panggilan moderasi pertama Anda. Dua metode integrasi didukung: SDK (disarankan) dan HTTPS native. Gunakan SDK bila memungkinkan—SDK secara otomatis menangani autentikasi signature dan pemformatan permintaan.
Prasyarat
Sebelum memulai, pastikan Anda telah memiliki:
-
Akun Alibaba Cloud dengan izin yang cukup untuk membuat pengguna RAM dan mengaktifkan layanan
Langkah 1: Aktifkan layanan
Buka halaman Aktifkan Layanan dan aktifkan Image Moderation 2.0.
Metode penagihan default adalah bayar sesuai pemakaian—biaya diselesaikan setiap hari berdasarkan penggunaan aktual. Jika Anda tidak melakukan panggilan API, Anda tidak dikenai biaya. Untuk detail harga, lihat Detail penagihan
Langkah 2: Buat pengguna RAM dan berikan izin
-
Login ke Konsol RAM menggunakan Akun Alibaba Cloud atau pengguna RAM admin Anda.
-
Buat pengguna RAM: pilih OpenAPI Access sebagai tipe akses, lalu catat Pasangan Kunci Akses yang dihasilkan. Lihat Buat pengguna RAM.
-
Berikan kebijakan sistem
AliyunYundunGreenWebFullAccesskepada pengguna RAM tersebut. Lihat Berikan izin kepada pengguna RAM.
Langkah 3: Siapkan kredensial
Simpan Pasangan Kunci Akses Anda sebagai variabel lingkungan agar kode Anda dapat membacanya tanpa menyimpan rahasia secara hardcoding.
Linux / macOS
export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>
Windows (Command Prompt)
set ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>
Ganti <your-access-key-id> dan <your-access-key-secret> dengan nilai dari Langkah 2.
Untuk opsi konfigurasi kredensial lainnya, lihat Konfigurasikan kredensial.
Langkah 4: Instal dan panggil SDK
Wilayah yang didukung
|
Wilayah |
Titik akhir publik |
Titik akhir VPC |
Kode layanan yang didukung |
|
Singapura |
green-cip.ap-southeast-1.aliyuncs.com |
green-cip-vpc.ap-southeast-1.aliyuncs.com |
postImageCheckByVL_global, baselineCheck_global, aigcDetector_global, faceDetect_global, faceDetect_pro_global |
|
Tiongkok (Hong Kong) |
green-cip.cn-hongkong.aliyuncs.com |
green-cip-vpc.cn-hongkong.aliyuncs.com |
postImageCheckByVL_cb, postImageCheckByVL_global |
|
Inggris (London) |
green-cip.eu-west-1.aliyuncs.com |
None |
|
|
AS (Virginia) |
green-cip.us-east-1.aliyuncs.com |
green-cip-vpc.us-east-1.aliyuncs.com |
baselineCheck_global, aigcDetector_global |
|
AS (Silicon Valley) |
green-cip.us-west-1.aliyuncs.com |
None |
|
|
Jerman (Frankfurt) |
green-cip.eu-central-1.aliyuncs.com |
green-cip-vpc.eu-central-1.aliyuncs.com |
Untuk contoh kode SDK dalam bahasa lain, gunakan OpenAPI Developer Portal untuk men-debug operasi API—portal ini secara otomatis menghasilkan contoh kode untuk setiap bahasa.
Pilih sumber gambar Anda
Parameter yang Anda kirimkan tergantung pada lokasi penyimpanan gambar Anda:
|
Sumber gambar |
Yang harus dilakukan |
|
URL yang dapat diakses publik |
Kirimkan URL langsung dalam permintaan |
|
File lokal (tanpa URL publik) |
Unggah terlebih dahulu ke bucket OSS Content Moderation, lalu kirimkan referensi objek OSS |
|
File yang sudah ada di bucket OSS Anda |
Berikan akses Content Moderation ke bucket Anda, lalu kirimkan referensi objek OSS |
Pahami respons
Setiap panggilan moderasi yang berhasil mengembalikan array Result yang berisi satu atau beberapa label. Setiap label memiliki dua bidang:
|
Bidang |
Deskripsi |
|
|
Kategori risiko yang terdeteksi (misalnya, |
|
|
Bilangan float antara 0 dan 100 yang menunjukkan tingkat kepercayaan terhadap label tersebut. Nilai yang lebih tinggi menunjukkan kepastian yang lebih tinggi. |
Contoh respons:
{
"Msg": "OK",
"Code": 200,
"Data": {
"DataId": "uimg123****",
"Result": [
{ "Label": "pornographic_adultContent", "Confidence": 81.3 },
{ "Label": "sexual_partialNudity", "Confidence": 98.9 }
]
},
"RequestId": "ABCD1234-1234-1234-1234-1234XYZ"
}
Java SDK
Persyaratan: Java 1.8 atau yang lebih baru
Kode sumber: Java SDK di GitHub
Deteksi gambar yang dapat diakses publik
Gambar yang dapat diakses melalui URL publik dapat dikirimkan langsung ke API.
-
Tambahkan dependensi ke
pom.xmlAnda:<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</version> </dependency> -
Panggil API:
Deteksi gambar lokal
Gambar lokal tanpa URL publik harus diunggah ke bucket OSS Content Moderation sebelum deteksi. Layanan akan mengambil gambar dari OSS untuk moderasi.
-
Tambahkan kedua dependensi ke
pom.xmlAnda:<!-- Content Moderation SDK --> <dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</version> </dependency> <!-- OSS SDK --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.16.3</version> </dependency> -
Panggil API:
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeUploadTokenResponse; import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody; import com.aliyun.green20220302.models.ImageModerationRequest; import com.aliyun.green20220302.models.ImageModerationResponse; import com.aliyun.green20220302.models.ImageModerationResponseBody; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class ScanLocalImage { // Set to true when running in a VPC environment. public static boolean isVPC = false; // Cache upload tokens by endpoint to avoid fetching a new token for every request. public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>(); public static OSS ossClient = null; public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); config.setEndpoint(endpoint); return new Client(config); } public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) { // Reuse the OSS client across requests. if (isVPC) { ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } else { ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } } public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception { String[] split = filePath.split("\\."); String objectName = split.length > 1 ? tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1] : tokenData.getFileNamePrefix() + UUID.randomUUID(); PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath)); ossClient.putObject(putObjectRequest); return objectName; } public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Reuse the client across requests. Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); // Replace with the actual path to your local file. String filePath = "D:\\localPath\\exampleFile.png"; // Fetch and cache the upload token; refresh it when it expires. if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) { DescribeUploadTokenResponse tokenResponse = client.describeUploadToken(); tokenMap.put(endpoint, tokenResponse.getBody().getData()); } getOssClient(tokenMap.get(endpoint), isVPC); String objectName = uploadFile(filePath, tokenMap.get(endpoint)); Map<String, String> serviceParameters = new HashMap<>(); serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName()); serviceParameters.put("ossObjectName", objectName); serviceParameters.put("dataId", UUID.randomUUID().toString()); ImageModerationRequest request = new ImageModerationRequest(); request.setService("baselineCheck_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); try { return client.imageModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) throws Exception { String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); if (response != null && response.getStatusCode() == 200) { ImageModerationResponseBody body = response.getBody(); System.out.println("requestId=" + body.getRequestId()); if (body.getCode() == 200) { ImageModerationResponseBodyData data = body.getData(); List<ImageModerationResponseBodyDataResult> results = data.getResult(); for (ImageModerationResponseBodyDataResult result : results) { System.out.println("label=" + result.getLabel()); System.out.println("confidence=" + result.getConfidence()); } } else { System.out.println("Moderation failed. code=" + body.getCode()); } } } }
Deteksi gambar OSS
Gambar yang sudah disimpan di bucket OSS Anda dapat dimoderasi secara langsung tanpa perlu diunggah ulang. Pertama, berikan akses Content Moderation ke bucket Anda dengan membuat peran layanan AliyunCIPScanOSSRole.
-
Login dengan akun Alibaba Cloud Anda (akun root) dan buka halaman Otorisasi Akses Sumber Daya Cloud untuk memberikan izin tersebut.
-
Tambahkan dependensi ke
pom.xmlAnda:<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</version> </dependency> -
Panggil API:
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.ImageModerationRequest; import com.aliyun.green20220302.models.ImageModerationResponse; import com.aliyun.green20220302.models.ImageModerationResponseBody; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class OssScanDemo { public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Optional: set HTTP/HTTPS proxy if needed // config.setHttpProxy("http://10.10.xx.xx:xxxx"); // config.setHttpsProxy("https://10.10.xx.xx:xxxx"); config.setEndpoint(endpoint); return new Client(config); } public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); Map<String, String> serviceParameters = new HashMap<>(); serviceParameters.put("dataId", UUID.randomUUID().toString()); serviceParameters.put("ossRegionId", "ap-southeast-1"); // region where the bucket is located serviceParameters.put("ossBucketName", "bucket001"); // your OSS bucket name serviceParameters.put("ossObjectName", "image/001.jpg"); // object path in the bucket ImageModerationRequest request = new ImageModerationRequest(); request.setService("baselineCheck_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); try { return client.imageModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) throws Exception { String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); if (response != null && response.getStatusCode() == 200) { ImageModerationResponseBody body = response.getBody(); System.out.println("requestId=" + body.getRequestId()); if (body.getCode() == 200) { ImageModerationResponseBodyData data = body.getData(); List<ImageModerationResponseBodyDataResult> results = data.getResult(); for (ImageModerationResponseBodyDataResult result : results) { System.out.println("label=" + result.getLabel()); System.out.println("confidence=" + result.getConfidence()); } } else { System.out.println("Moderation failed. code=" + body.getCode()); } } } }
Python SDK
Persyaratan: Python 3.6 atau yang lebih baru
Kode sumber: Python SDK di PyPI
Deteksi gambar yang dapat diakses publik
-
Instal SDK:
pip install alibabacloud_green20220302==3.2.4 -
Panggil API:
# coding=utf-8 import json import os import uuid from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util import models as util_models def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Optional: set HTTP/HTTPS proxy if needed # http_proxy='http://10.10.xx.xx:xxxx', # https_proxy='https://10.10.xx.xx:xxxx', endpoint=endpoint ) return Client(config) def invoke_function(access_key_id, access_key_secret, endpoint): # Reuse the client across requests. client = create_client(access_key_id, access_key_secret, endpoint) runtime = util_models.RuntimeOptions() service_parameters = { 'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png', # public URL 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Set the service code configured in the AI Guardrails console. service='baselineCheck_global', service_parameters=json.dumps(service_parameters) ) try: return client.image_moderation_with_options(image_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__main__': # Read credentials from environment variables — do not hardcode them. access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] # Change the endpoint to match your region. response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') if response is not None and response.status_code == 200: result = response.body if result.code == 200: result_data = result.data print('result:', result_data) else: print('Moderation failed. status:', response.status_code)
Deteksi gambar lokal
-
Instal kedua SDK:
pip install alibabacloud_green20220302==3.2.4 pip install oss2 -
Panggil API:
import json import os import time import uuid import oss2 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util import models as util_models # Set to True when running in a VPC environment. is_vpc = False # Cache upload tokens by endpoint to avoid fetching a new token for every request. token_dict = dict() bucket = None def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, endpoint=endpoint ) return Client(config) def create_oss_bucket(is_vpc, upload_token): global bucket auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token) end_point = upload_token.oss_internal_end_point if is_vpc else upload_token.oss_internet_end_point # Reuse the bucket client across requests. bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name) def upload_file(file_name, upload_token): create_oss_bucket(is_vpc, upload_token) object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1] bucket.put_object_from_file(object_name, file_name) return object_name def invoke_function(access_key_id, access_key_secret, endpoint): client = create_client(access_key_id, access_key_secret, endpoint) runtime = util_models.RuntimeOptions() # Replace with the actual path to your local file. file_path = 'D:\\localPath\\exampleFile.png' # Fetch and cache the upload token; refresh it when it expires. upload_token = token_dict.setdefault(endpoint, None) if upload_token is None or int(upload_token.expiration) <= int(time.time()): response = client.describe_upload_token() upload_token = response.body.data token_dict[endpoint] = upload_token object_name = upload_file(file_path, upload_token) service_parameters = { 'ossBucketName': upload_token.bucket_name, 'ossObjectName': object_name, 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( service='baselineCheck_global', service_parameters=json.dumps(service_parameters) ) try: return client.image_moderation_with_options(image_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__main__': access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') if response is not None and response.status_code == 200: result = response.body if result.code == 200: print('result:', result.data) else: print('Moderation failed. status:', response.status_code)
Deteksi gambar OSS
-
Berikan akses Content Moderation ke bucket OSS Anda: login dengan akun Alibaba Cloud Anda (akun root) dan buka halaman Otorisasi Akses Sumber Daya Cloud untuk membuat peran layanan AliyunCIPScanOSSRole.
-
Instal SDK:
pip install alibabacloud_green20220302==3.2.4 -
Panggil API:
import json import os import uuid from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util import models as util_models def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, endpoint=endpoint ) return Client(config) def invoke_function(access_key_id, access_key_secret, endpoint): client = create_client(access_key_id, access_key_secret, endpoint) runtime = util_models.RuntimeOptions() service_parameters = { 'ossRegionId': 'ap-southeast-1', # region where the bucket is located 'ossBucketName': 'bucket001', # your OSS bucket name 'ossObjectName': 'image/001.jpg', # object path in the bucket 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( service='baselineCheck_global', service_parameters=json.dumps(service_parameters) ) try: return client.image_moderation_with_options(image_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__main__': access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') if response is not None and response.status_code == 200: result = response.body if result.code == 200: print('result:', result.data) else: print('Moderation failed. status:', response.status_code)
PHP SDK
Persyaratan: PHP 5.6 atau yang lebih baru
Kode sumber: PHP SDK di Packagist
Deteksi gambar yang dapat diakses publik
-
Instal SDK:
composer require alibabacloud/green-20220302 3.2.4 -
Panggil API:
Deteksi gambar lokal
-
Instal kedua SDK:
composer require alibabacloud/green-20220302 3.2.4 composer require aliyuncs/oss-sdk-php -
Panggil API:
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest; use OSS\OssClient; // Set to true when running in a VPC environment. $isVPC = false; // Cache upload tokens by endpoint. $tokenArray = array(); $ossClient = null; function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, "endpoint" => $endpoint, ]); return new Green($config); } function create_upload_client($tokenData): void { global $isVPC, $ossClient; // Reuse the OSS client across requests. if ($isVPC) { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken); } else { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken); } } function upload_file($filePath, $tokenData): string { global $ossClient; create_upload_client($tokenData); $split = explode(".", $filePath); $objectName = count($split) > 1 ? $tokenData->fileNamePrefix . uniqid() . "." . end($split) : $tokenData->fileNamePrefix . uniqid(); $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath); return $objectName; } function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { global $tokenArray; $client = create_client($accessKeyId, $accessKeySecret, $endpoint); $runtime = new RuntimeOptions([]); // Replace with the actual path to your local file. $filePath = "D:\\localPath\\exampleFile.png"; // Fetch and cache the upload token; refresh it when it expires. if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) { $token = $client->describeUploadToken(); $tokenArray[$endpoint] = $token->body->data; } $objectName = upload_file($filePath, $tokenArray[$endpoint]); $request = new ImageModerationRequest(); $request->service = "baselineCheck_global"; $serviceParameters = array( 'ossObjectName' => $objectName, 'ossBucketName' => $tokenArray[$endpoint]->bucketName, 'dataId' => uniqid() ); $request->serviceParameters = json_encode($serviceParameters); return $client->imageModerationWithOptions($request, $runtime); } $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); $endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; try { $response = invoke($accessKeyId, $accessKeySecret, $endpoint); print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE)); } catch (Exception $e) { var_dump($e->getMessage()); }
Deteksi gambar OSS
-
Berikan akses Content Moderation ke bucket OSS Anda: login dengan akun Alibaba Cloud Anda (akun root) dan buka halaman Otorisasi Akses Sumber Daya Cloud untuk membuat peran layanan AliyunCIPScanOSSRole.
-
Instal SDK:
composer require alibabacloud/green-20220302 3.2.4 -
Panggil API:
Go SDK
Kode sumber: Go SDK di GitHub
Deteksi gambar yang dapat diakses publik
-
Instal SDK:
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4 -
Panggil API:
Deteksi gambar lokal
-
Instal kedua SDK:
go get github.com/alibabacloud-go/green-20220302/v3 go get github.com/aliyun/aliyun-oss-go-sdk/oss -
Panggil API:
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/google/uuid" "net/http" "os" "strings" "time" ) // Cache upload tokens by endpoint. var TokenMap = make(map[string]*green20220302.DescribeUploadTokenResponseBodyData) // Set to true when running in a VPC environment. var isVPC = false var Bucket *oss.Bucket func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: tea.String(accessKeyId), AccessKeySecret: tea.String(accessKeySecret), Endpoint: tea.String(endpoint), } return green20220302.NewClient(config) } func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) { var endPoint string if isVPC { endPoint = tea.StringValue(tokenData.OssInternalEndPoint) } else { endPoint = tea.StringValue(tokenData.OssInternetEndPoint) } ossClient, err := oss.New(endPoint, tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ = ossClient.Bucket(tea.StringValue(tokenData.BucketName)) } func uploadFile(filePath string, tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string, error) { createOssClient(tokenData) objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1] _err := Bucket.PutObjectFromFile(objectName, filePath) if _err != nil { fmt.Println("Error:", _err) os.Exit(-1) } return objectName, _err } func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.ImageModerationResponse, _err error) { client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil, _err } runtime := &util.RuntimeOptions{} // Replace with the actual path to your local file. var filePath = "D:\\localPath\\exampleFile.png" // Fetch and cache the upload token; refresh it when it expires. tokenData, ok := TokenMap[endpoint] if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) { uploadTokenResponse, _err := client.DescribeUploadToken() if _err != nil { return nil, _err } tokenData = uploadTokenResponse.Body.Data TokenMap[endpoint] = tokenData } objectName, _ := uploadFile(filePath, TokenMap[endpoint]) serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName), "ossObjectName": objectName, "dataId": uuid.New().String(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") endpoint := "green-cip.ap-southeast-1.aliyuncs.com" response, _err := invoke(accessKeyId, accessKeySecret, endpoint) if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body fmt.Println("requestId:" + tea.StringValue(body.RequestId)) if statusCode == http.StatusOK { if tea.IntValue(tea.ToInt(body.Code)) == 200 { result := body.Data.Result for i := 0; i < len(result); i++ { fmt.Println("label:" + tea.StringValue(result[i].Label)) fmt.Println("confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence))) } } else { fmt.Println("Moderation failed. code:", body.Code) } } else { fmt.Println("Request failed. status:", statusCode, "error:", _err) } } }
Deteksi gambar OSS
-
Berikan akses Content Moderation ke bucket OSS Anda: login dengan akun Alibaba Cloud Anda (akun root) dan buka halaman Otorisasi Akses Sumber Daya Cloud untuk membuat peran layanan AliyunCIPScanOSSRole.
-
Instal SDK:
go get github.com/alibabacloud-go/green-20220302/v3 -
Panggil API:
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/google/uuid" "net/http" "os" ) func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, Endpoint: endpoint, } return green20220302.NewClient(config) } func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) { client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil, _err } runtime := &util.RuntimeOptions{} serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossRegionId": "ap-southeast-1", // region where the bucket is located "ossBucketName": "bucket001", // your OSS bucket name "ossObjectName": "image/001.jpg", // object path in the bucket "dataId": uuid.New().String(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { accessKeyId := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) accessKeySecret := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) endpoint := tea.String("green-cip.ap-southeast-1.aliyuncs.com") response, _err := invoke(accessKeyId, accessKeySecret, endpoint) if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body fmt.Println("requestId:" + tea.StringValue(body.RequestId)) if statusCode == http.StatusOK { if tea.IntValue(tea.ToInt(body.Code)) == 200 { result := body.Data.Result for i := 0; i < len(result); i++ { fmt.Println("label:" + tea.StringValue(result[i].Label)) fmt.Println("confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence))) } } else { fmt.Println("Moderation failed. code:", body.Code) } } else { fmt.Println("Request failed. status:", statusCode, "error:", _err) } } }
Node.js SDK
Kode sumber: Node.js SDK di npm
Deteksi gambar yang dapat diakses publik
-
Instal SDK:
npm install @alicloud/green20220302@3.2.4 -
Panggil API:
const RPCClient = require("@alicloud/pop-core"); const { v4: uuidv4 } = require('uuid'); async function main() { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. var client = new RPCClient({ /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable', accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable', // Modify the region and endpoint as needed. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02', // Set the HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Set the HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); // Create an API request and set parameters. var params = { // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck_global "Service": "baselineCheck_global", // OSS information of the image to be detected. "ServiceParameters": JSON.stringify({ // The region where the bucket of the file to be detected is located. Example: ap-southeast-1 "ossRegionId": "ap-southeast-1", // The name of the bucket where the file to be detected is located. Example: bucket001 "ossBucketName": "bucket001", // The file to be detected. Example: image/001.jpg "ossObjectName": "image/001.jpg", // A unique identifier for the data. "dataId": uuidv4() }) } var requestOption = { method: 'POST', formatParams: false, }; try { // Call the API operation to get the detection results. var response = await client.request('ImageModeration', params, requestOption) return response; } catch (err) { console.log(err); } } main().then(function (response) { console.log(JSON.stringify(response)) });
Deteksi gambar lokal
-
Instal kedua dependensi:
npm install @alicloud/green20220302@3.2.4 npm install ali-oss --save -
Panggil API:
const RPCClient = require("@alicloud/pop-core"); const OSS = require('ali-oss'); const { v4: uuidv4 } = require('uuid'); const path = require("path"); // Specifies whether the service is deployed in a VPC. var isVPC = false; // File upload token. var tokenDic = new Array(); // Client for file uploads. var ossClient; // Create a client for file uploads. function createClient(accessKeyId, accessKeySecret, endpoint) { return new RPCClient({ accessKeyId: accessKeyId, accessKeySecret: accessKeySecret, endpoint: endpoint, apiVersion: '2022-03-02', // Set the HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Set the HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); } // Create a client for file uploads. function getOssClient(tokenData, isVPC) { if (isVPC) { ossClient = new OSS({ accessKeyId: tokenData['AccessKeyId'], accessKeySecret: tokenData['AccessKeySecret'], stsToken: tokenData['SecurityToken'], endpoint: tokenData['OssInternalEndPoint'], bucket: tokenData['BucketName'], }); } else { ossClient = new OSS({ accessKeyId: tokenData['AccessKeyId'], accessKeySecret: tokenData['AccessKeySecret'], stsToken: tokenData['SecurityToken'], endpoint: tokenData['OssInternetEndPoint'], bucket: tokenData['BucketName'], }); } } async function invoke(accessKeyId, accessKeySecret, endpoint) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. var client = createClient(accessKeyId, accessKeySecret, endpoint); var requestOption = { method: 'POST', formatParams: false, }; // The full path of the local file, for example, D:\\localPath\\exampleFile.png. var filePath = 'D:\\localPath\\exampleFile.png'; // Get the file upload token. if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.request('DescribeUploadToken', '', requestOption) tokenDic[endpoint] = tokenResponse.Data; } // Get the client for file uploads. getOssClient(tokenDic[endpoint], isVPC) var split = filePath.split("."); var objectName; if (split.length > 1) { objectName = tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1]; } else { objectName = tokenDic[endpoint].FileNamePrefix + uuidv4(); } // Upload the file. const result = await ossClient.put(objectName, path.normalize(filePath)); // Create a detection API request and set parameters. var params = { // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck_global "Service": "baselineCheck_global", // Information about the uploaded local image. "ServiceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].BucketName, "ossObjectName": objectName }) } // Call the API operation to get the detection results. return await client.request('ImageModeration', params, requestOption); } function main() { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ const accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable' const accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable' // Modify the region and endpoint as needed. var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com" try { // Call the API operation to get the detection results. invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) { console.log(JSON.stringify(response)) }) } catch (err) { console.log(err); } } main();
Deteksi gambar OSS
-
Berikan akses Content Moderation ke bucket OSS Anda: login dengan akun Alibaba Cloud Anda (akun root) dan buka halaman Otorisasi Akses Sumber Daya Cloud untuk membuat peran layanan AliyunCIPScanOSSRole.
-
Instal SDK:
npm install @alicloud/green20220302@3.2.4 -
Panggil API:
const RPCClient = require("@alicloud/pop-core"); const { v4: uuidv4 } = require('uuid'); async function main() { var client = new RPCClient({ accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02', }); var params = { "Service": "baselineCheck_global", "ServiceParameters": JSON.stringify({ "ossRegionId": "ap-southeast-1", // region where the bucket is located "ossBucketName": "bucket001", // your OSS bucket name "ossObjectName": "image/001.jpg", // object path in the bucket "dataId": uuidv4() }) }; var requestOption = { method: 'POST', formatParams: false }; try { var response = await client.request('ImageModeration', params, requestOption); return response; } catch (err) { console.log(err); } } main().then(function (response) { console.log(JSON.stringify(response)); });
C# SDK
Kode sumber: C# SDK di NuGet
Deteksi gambar yang dapat diakses publik
-
Instal SDK:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4 -
Panggil API:
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace AlibabaCloud.SDK.Green20220302 { public class ImageModerationAutoRoute { public static void Main(string[] args) { // Read credentials from environment variables — do not hardcode them. string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Change the endpoint to match your region. string endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Reuse the client across requests. Client client = createClient(accessKeyId, accessKeySecret, endpoint); AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Set the service code configured in the AI Guardrails console. imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); task.Add("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); // public URL task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); try { Models.ImageModerationResponse response = client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception err) { Console.WriteLine(err); } } public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Optional: set HTTP/HTTPS proxy if needed // HttpProxy = "http://10.10.xx.xx:xxxx", // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", Endpoint = endpoint, }; return new Client(config); } } }
Deteksi gambar lokal
Instal SDK Content Moderation dan SDK OSS:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
Untuk SDK OSS, instal melalui NuGet di Visual Studio:
-
Buka Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
-
Cari
aliyun.oss.sdk. -
Pilih Aliyun.OSS.SDK (untuk .NET Framework) atau Aliyun.OSS.SDK.NetCore (untuk .NET Core) dan klik Install.
Kemudian panggil API:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Aliyun.OSS;
namespace AlibabaCloud.SDK.Green20220302
{
public class ImageModerationAutoRoute
{
// Cache upload tokens by endpoint.
public static Dictionary<string, Models.DescribeUploadTokenResponse> tokenDic =
new Dictionary<string, Models.DescribeUploadTokenResponse>();
public static OssClient ossClient = null;
// Set to true when running in a VPC environment.
public static bool isVPC = false;
public static void Main(string[] args)
{
string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
string endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
Models.ImageModerationResponse response = invoke(accessKeyId, accessKeySecret, endpoint);
Console.WriteLine(response.Body.RequestId);
Console.WriteLine(JsonConvert.SerializeObject(response.Body));
}
public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
Endpoint = endpoint,
};
return new Client(config);
}
private static OssClient getOssClient(Models.DescribeUploadTokenResponse tokenResponse, bool isVPC)
{
var tokenData = tokenResponse.Body.Data;
return isVPC
? new OssClient(tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken)
: new OssClient(tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken);
}
public static string uploadFile(string filePath, Models.DescribeUploadTokenResponse tokenResponse)
{
ossClient = getOssClient(tokenResponse, isVPC);
var tokenData = tokenResponse.Body.Data;
string objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split(".").GetValue(1);
ossClient.PutObject(tokenData.BucketName, objectName, filePath);
return objectName;
}
public static Models.ImageModerationResponse invoke(string accessKeyId, string accessKeySecret, string endpoint)
{
// Reuse the client across requests.
Client client = createClient(accessKeyId, accessKeySecret, endpoint);
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
// Replace with the actual path to your local file.
string filePath = "D:\\localPath\\exampleFile.png";
try
{
// Fetch and cache the upload token; refresh it when it expires.
if (!tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds())
{
tokenDic[endpoint] = client.DescribeUploadToken();
}
string objectName = uploadFile(filePath, tokenDic[endpoint]);
Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
imageModerationRequest.Service = "baselineCheck_global";
Dictionary<string, object> task = new Dictionary<string, object>();
task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
task.Add("ossObjectName", objectName);
task.Add("dataId", Guid.NewGuid().ToString());
imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
return client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
}
catch (Exception err)
{
Console.WriteLine(err);
return null;
}
}
}
}
Deteksi gambar OSS
-
Berikan akses Content Moderation ke bucket OSS Anda: login dengan akun Alibaba Cloud Anda (akun root) dan buka halaman Otorisasi Akses Sumber Daya Cloud untuk membuat peran layanan AliyunCIPScanOSSRole.
-
Instal SDK:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4 -
Panggil API:
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace AlibabaCloud.SDK.Green20220302 { public class OssScanDemo { public static void Main(string[] args) { string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); string endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; Client client = createClient(accessKeyId, accessKeySecret, endpoint); AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); task.Add("ossRegionId", "ap-southeast-1"); // region where the bucket is located task.Add("ossBucketName", "bucket001"); // your OSS bucket name task.Add("ossObjectName", "image/001.jpg"); // object path in the bucket task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); try { Models.ImageModerationResponse response = client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception err) { Console.WriteLine(err); } } public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, Endpoint = endpoint, }; return new Client(config); } } }
Panggilan HTTPS native
Gunakan panggilan HTTPS native hanya ketika SDK tidak sesuai untuk lingkungan Anda:
-
Aplikasi Anda memiliki batasan ukuran ketat pada dependensi klien.
-
Anda bergantung pada versi library tertentu yang tidak dapat ditingkatkan.
Dengan HTTPS native, Anda harus secara manual membuat URL permintaan, menghitung signature HMAC-SHA1, dan menyusun semua parameter permintaan.
Titik akhir dan protokol
-
Titik akhir:
https://green-cip.{region}.aliyuncs.com -
Protokol: HTTPS
-
Metode: POST
Parameter permintaan umum
Setiap permintaan memerlukan parameter berikut:
|
Parameter |
Tipe |
Wajib |
Deskripsi |
|
|
String |
Ya |
Format respons: |
|
|
String |
Ya |
Versi API dalam format YYYY-MM-DD. Nilai: |
|
|
String |
Ya |
ID AccessKey Anda |
|
|
String |
Ya |
String signature HMAC-SHA1 |
|
|
String |
Ya |
Algoritma signature: |
|
|
String |
Ya |
Waktu permintaan dalam format ISO 8601 UTC: |
|
|
String |
Ya |
Versi algoritma signature: |
|
|
String |
Ya |
Bilangan acak unik untuk mencegah serangan replay; gunakan nilai berbeda untuk setiap permintaan |
|
|
String |
Ya |
API yang dipanggil: |
Parameter respons umum
Setiap respons mencakup RequestId terlepas dari keberhasilan panggilan. Array Data.Result berisi bidang Label dan Confidence. Lihat format respons dan deskripsi bidang di bagian SDK di atas.
Contoh permintaan
Contoh berikut memanggil API deteksi baseline sinkron:
https://green-cip.ap-southeast-1.aliyuncs.com/
?Format=JSON
&Version=2022-03-02
&Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
&SignatureMethod=Hmac-SHA1
&SignatureNonce=15215528852396
&SignatureVersion=1.0
&Action=ImageModeration
&AccessKeyId=123****cip
&Timestamp=2022-12-12T12:00:00Z
&Service=baselineCheck_global
&ServiceParameters={"imageUrl": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png",
"dataId": "img1234567"}
Hitung signature
Image Moderation 2.0 menggunakan HMAC-SHA1 untuk mengotentikasi setiap permintaan.
Langkah 1: Buat string kueri terkanonisasi
-
Urutkan semua parameter permintaan secara alfabet berdasarkan nama parameter (kecuali
Signature). -
Encode URL setiap nama dan nilai parameter menggunakan UTF-8 dan aturan berikut:
-
Jangan encode:
A–Z,a–z,0–9, tanda hubung (-), garis bawah (_), titik (.), tilde (~) -
Encode karakter lain sebagai
%XY(ASCII heksadesimal) -
Encode spasi sebagai
%20, bukan+; encode*sebagai%2A; ganti%7Edengan~ -
Encode karakter UTF-8 yang diperluas sebagai
%XY%ZA…
Pustaka encoding URL standar (seperti
java.net.URLEncoder) menggunakan aturan tipe MIMEapplication/x-www-form-urlencoded. Setelah encoding, ganti+dengan%20,*dengan%2A, dan%7Edengan~. -
-
Hubungkan setiap pasangan nama–nilai yang telah diencode dengan
=. -
Hubungkan semua pasangan dalam urutan alfabet dengan
&untuk mendapatkan string kueri terkanonisasi.
Langkah 2: Buat string yang akan ditandatangani
StringToSign = HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)
Di mana percentEncode("/") adalah %2F, dan HTTPMethod adalah POST.
Langkah 3: Hitung nilai HMAC-SHA1
Sesuai definisi dalam RFC 2104, hitung hash HMAC-SHA1 dari StringToSign. Kunci penandatanganan adalah rahasia AccessKey Anda diikuti dengan & (ASCII 38).
Langkah 4: Encode hasilnya
Encode nilai HMAC-SHA1 dalam Base64 untuk mendapatkan string Signature.
Langkah 5: Tambahkan signature ke permintaan
Tambahkan Signature sebagai parameter kueri yang diencode URL menggunakan aturan encoding RFC 3986.
Apa selanjutnya
-
Referensi API Image Moderation 2.0 — dokumentasi parameter lengkap dan semua operasi API
-
Deskripsi label risiko — daftar lengkap label dan maknanya
-
Konfigurasikan kredensial — opsi konfigurasi kredensial lainnya
-
Detail penagihan — harga dan siklus penagihan