This document describes how to use the Java SDK for the Alibaba Cloud Vision AI Platform, including how to install the SDK and use code examples.
For assistance with SDK integration, API usage, or other issues related to the AI capabilities of the Alibaba Cloud Vision AI Platform, join our DingTalk support group (ID: 23109592).
This SDK version requires Java 8 or later. If your environment does not meet this requirement, upgrade your Java version.
Download the SDK package for the service you need. The following table lists the SDK package names for each service.
AI category | SDK package name | SDK link | GitHub link |
face and body | facebody20191230 | ||
text recognition | ocr20191230 | ||
product understanding | goodstech20191230 | ||
content moderation | imageaudit20191230 | ||
image recognition | imagerecog20190930 | ||
image enhancement | imageenhan20190930 | ||
image segmentation | imageseg20191230 | ||
object detection | objectdet20191230 | ||
visual search | imgsearch20200320 | ||
image analysis and processing | imageprocess20200320 | ||
video understanding | videorecog20200320 | ||
video enhancement | videoenhan20200320 | ||
video segmentation | videoseg20200320 | ||
asynchronous task management | viapi20230117 | ||
face verification server 20200910 dedicated version | facebody20200910 |
Prerequisites
Before you use the Alibaba Cloud SDK, make sure you have registered an Alibaba Cloud account and created an AccessKey.
The Java SDK for the relevant Vision AI Platform service is installed.
Check the SDK version
The version value in your pom.xml file should be the latest version available. You can check the version for each service's SDK at https://mvnrepository.com/artifact/com.aliyun/.
For example, you can visit https://mvnrepository.com/artifact/com.aliyun/facebody20191230 to check the version of facebody20191230.
Installation method 1: Use Maven (Recommended)
If you use Maven to manage your Java project, you can install the Java SDK by adding a dependency to the pom.xml file. For example, if you need capabilities from the face and body category, add the dependency for facebody20191230.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>facebody20191230</artifactId>
<version>${aliyun.facebody.version}</version>
</dependency>Installation method 2: Import JAR into IDE
You can install the Java SDK in Eclipse or IntelliJ by importing a JAR file.
Install in Eclipse
Copy the downloaded
xxx.jarfile and its dependencies to your project folder.In Eclipse, open your project, right-click the project, and then select Properties.
In the dialog box that appears, click Java Build Path > Libraries > Add JARs to add the downloaded JAR file.
Click Apply and Close.
Install in IntelliJ
Copy the downloaded
xxx.jarfile and its dependencies to your project folder.In IntelliJ, open your project, right-click the
xxx.jarfile, and then select Add as Library.Click Apply, and then click OK.
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.
Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
Configure environment variables on Linux and macOS
Open a terminal in IntelliJ IDEA.
Run the following commands to configure the environment variables.
Replace
<access_key_id>with the AccessKey ID of your RAM user and<access_key_secret>with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Configure environment variables on Windows
Create a new environment variable file, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.Open File Explorer, right-click This PC, and then select Properties.
In the left-side navigation pane, click Advanced system settings.
On the Advanced tab of the System Properties dialog box, click Environment Variables.
In the Environment Variables dialog box, click New.
In the New System Variable dialog box, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.Restart the Windows operating system for the configurations to take effect.
SDK example
This topic uses the RecognizeBankCard operation as an example.
File in an OSS bucket
For information about the endpoints and supported regions for each service category, see Endpoints.
package com.aliyun.sample;
// 1. This example uses the RecognizeBankCard operation from the text recognition category. For other operations, import the corresponding packages and classes. You can find the package name in the SDK package name table and the action name in the corresponding API documentation. For example, to use image segmentation (SegmentCommonImage), as described in https://help.aliyun.com/document_detail/151960.html, change ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage.
import com.aliyun.ocr20191230.models.RecognizeBankCardResponse;
import com.aliyun.tea.*;
public class Sample {
/**
* Initializes a client object by using an AccessKey pair.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
// This example uses the ocr category. For other operations, use the Client class from the corresponding package.
public static com.aliyun.ocr20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initializes a com.aliyun.teaopenapi.models.Config object.
The Config object stores configurations such as the AccessKey ID, AccessKey Secret, and endpoint.
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// 2. The endpoint. You must change this to the endpoint of the corresponding service category. For more information, see https://help.aliyun.com/document_detail/143103.html.
config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
// 3. This example uses the ocr category. For other operations, use the Client class from the corresponding package.
return new com.aliyun.ocr20191230.Client(config);
}
public static void main(String[] args) throws Exception {
// 4. For information about how to create an AccessKey pair, see https://help.aliyun.com/document_detail/175144.html.
// If you are using a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
// The AccessKey ID and AccessKey Secret are read from environment variables. You must configure the environment variables before you run the code.
// This example uses the ocr category. For other operations, use the Client class from the corresponding package.
com.aliyun.ocr20191230.Client client = Sample.createClient(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// 5. This example uses the RecognizeBankCard operation from the ocr category. For other operations, use the corresponding packages and classes. For information about how to set the input parameters, see the documentation for the specific operation.
com.aliyun.ocr20191230.models.RecognizeBankCardRequest recognizeBankCardRequest = new com.aliyun.ocr20191230.models.RecognizeBankCardRequest()
.setImageURL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 6. This example uses the RecognizeBankCard operation from the ocr category. For other operations, use the corresponding package and class. You also need to change the method name. The method name is generated based on the operation name. For example, if the operation name is SegmentCommonImage, the method name is segmentCommonImageWithOptions.
RecognizeBankCardResponse resp = client.recognizeBankCardWithOptions(recognizeBankCardRequest, runtime);
// Get the complete result. Some operations may return a URL. The URL may have encoding issues when converted by using toJSONString, but you can retrieve individual fields without issues.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
// Get a single field. This is just an example. For the specific fields of an operation, see the documentation for that operation.
System.out.println(resp.getBody().getData().getCardNumber());
} catch (com.aliyun.tea.TeaException teaException) {
// Get the complete error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Get a single field from the error message.
System.out.println(teaException.getCode());
}
}
}The code comments highlight the required modifications, which are summarized below:
When you import packages, make sure to import the packages and classes for the correct service category. You can find the package name in the SDK package name table and the operation name (which corresponds to the Action parameter) in the API documentation for the operation.
For example, to use the image segmentation feature, you can find in the SegmentCommonImage API documentation that the operation belongs to the image segmentation (imageseg20191230) category and the operation name is SegmentCommonImage. You need to change
ocr20191230toimageseg20191230andRecognizeBankCardtoSegmentCommonImagein your code.Make sure to change the endpoint to the one that corresponds to the service category. If the endpoint and category do not match, an
InvalidAction.NotFounderror is returned. For more information about endpoints, see Endpoints.Use the
Clientclass from the package of the corresponding service category.Use the
RequestandResponseobjects from the packages and classes of the corresponding service category.When you call a client method, change the method name to match the operation. The method name is generated based on the operation name. For example, if the operation name is SegmentCommonImage, the corresponding method name is segmentCommonImageWithOptions.
Local file or public URL
The main difference from the previous scenario is the use of an xxxAdvanceRequest object. The file is passed as a stream through the ImageURLObject parameter.
package com.aliyun.sample;
// 1. This example uses the RecognizeBankCard operation from the text recognition category. For other operations, import the corresponding packages and classes. You can find the package name in the SDK package name table and the action name in the corresponding API documentation. For example, to use image segmentation (SegmentCommonImage), as described in https://help.aliyun.com/document_detail/151960.html, change ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage.
import com.aliyun.ocr20191230.models.RecognizeBankCardResponse;
import com.aliyun.tea.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Sample {
/**
* Initializes a client object by using an AccessKey pair.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
// This example uses the ocr category. For other operations, use the Client class from the corresponding package.
public static com.aliyun.ocr20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initializes a com.aliyun.teaopenapi.models.Config object.
The Config object stores configurations such as the AccessKey ID, AccessKey Secret, and endpoint.
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// 2. The endpoint. You must change this to the endpoint of the corresponding service category. For more information, see https://help.aliyun.com/document_detail/143103.html.
config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
// 3. This example uses the ocr category. For other operations, use the Client class from the corresponding package.
return new com.aliyun.ocr20191230.Client(config);
}
public static void main(String[] args) throws Exception {
// 4. For information about how to create an AccessKey pair, see https://help.aliyun.com/document_detail/175144.html.
// If you are using a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
// The AccessKey ID and AccessKey Secret are read from environment variables. You must configure the environment variables before you run the code.
// This example uses the ocr category. For other operations, use the Client class from the corresponding package.
com.aliyun.ocr20191230.Client client = Sample.createClient(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Scenario 1: Use a local file.
// InputStream inputStream = new FileInputStream(new File("/tmp/bankCard.png"));
// Scenario 2: Use any publicly accessible URL.
URL url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg");
InputStream inputStream = url.openConnection().getInputStream();
// 5. This example uses the RecognizeBankCard operation from the ocr category. For other operations, use the corresponding packages and classes. For information about how to set the input parameters, see the documentation for the specific operation.
com.aliyun.ocr20191230.models.RecognizeBankCardAdvanceRequest recognizeBankCardAdvanceRequest = new com.aliyun.ocr20191230.models.RecognizeBankCardAdvanceRequest()
.setImageURLObject(inputStream);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 6. This example uses the RecognizeBankCard operation from the ocr category. For other operations, use the corresponding package and class. You also need to change the method name to recognizeBankCardAdvance. The method name is generated based on the operation name. For example, if the operation name is SegmentCommonImage, the method name is segmentCommonImageAdvance.
RecognizeBankCardResponse resp = client.recognizeBankCardAdvance(recognizeBankCardAdvanceRequest, runtime);
// Get the complete result. Some operations may return a URL. The URL may have encoding issues when converted by using toJSONString, but you can retrieve individual fields without issues.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
// Get a single field. This is just an example. For the specific fields of an operation, see the documentation for that operation.
System.out.println(resp.getBody().getData().getCardNumber());
} catch (com.aliyun.tea.TeaException teaException) {
// Get the complete error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Get a single field from the error message.
System.out.println(teaException.getCode());
}
}
}The required modifications are marked in the code comments. A summary is provided below:
When you import packages, make sure to import the packages and classes for the correct service category. You can find the package name in the SDK package name table and the operation name (which corresponds to the Action parameter) in the API documentation for the operation.
For example, to use the image segmentation feature, you can find in the SegmentCommonImage API documentation that the operation belongs to the image segmentation (imageseg20191230) category and the operation name is SegmentCommonImage. You need to change
ocr20191230toimageseg20191230andRecognizeBankCardtoSegmentCommonImagein your code.Make sure to change the endpoint to the one that corresponds to the service category. If the endpoint and category do not match, an
InvalidAction.NotFounderror is returned. For more information about endpoints, see Endpoints.Use the
Clientclass from the package of the corresponding service category.Use the
RequestandResponseobjects from the packages and classes of the corresponding service category.When you call a client method, change the method name to match the operation. The method name is generated based on the operation name. For example, if the operation name is SegmentCommonImage, the corresponding method name is segmentCommonImageAdvance.
FAQ
API call failures
If an API call fails, first try to update the SDK package to the latest version. For the latest version, refer to the SDK links for each category. If your program imports packages from multiple categories, try updating all of them to their latest versions to avoid version conflicts. The failure might also be a dependency conflict with an existing package, which you can resolve by using a Maven dependency analysis tool.
Latest package not in Maven repository
If you cannot find the latest package version from the OpenAPI Portal in the Maven repository, it may be due to a synchronization delay after a recent release. If the version does not exist, try again later or use the latest version available in the Maven repository.
Android development
Yes. For information on calling the SDK from an Android client, see Call the API on an Android client.
HTTPS request failures due to certificates
Error message
Exception in thread "main" javax.net.ssl.SSLException: java.net.SocketException: Connection reset
at sun.security.ssl.Alert.createSSLException(Alert.java:127)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:370)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:313)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:308)
at sun.security.ssl.SSLTransport.decode(SSLTransport.java:141)
at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1298)
at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1199)
Solution
In the upgraded SDK, you can set the request protocol for the OpenAPI client. This setting overrides the default. For more information about ignoring certificates, see Configure HTTPS requests.
NoSuchMethodError with xxxAdvanceRequest
Error message
Exception in thread "main" java.lang.NoSuchMethodError: com.aliyun.credentials.Client.getCredential()Lcom/aliyun/credentials/models/CredentialModel;
at com.aliyun.teaopenapi.Client.doRequest(Client.java:814)
at com.aliyun.teaopenapi.Client.callApi(Client.java:1083)
at com.aliyun.openplatform20191219.Client.authorizeFileUploadWithOptions(Client.java:46)
at com.aliyun.facebody20191230.Client.compareFaceAdvance(Client.java:894)
at com.test.CompareFace.main(CompareFace.java:56)Solution
This error is caused by a dependency conflict. To resolve the issue, update the credentials package to the latest version by using the following dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/credentials-java -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>${aliyun.credentials.version}</version>
</dependency>Technical support
If the methods above do not resolve your issue, join the Alibaba Cloud Vision AI Platform support group on DingTalk by searching for the group ID 23109592. Our technical staff will help you resolve the issue.