Java

更新时间:
复制 MD 格式

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.

Note

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

Aliyun Java SDK Facebody

facebody-20191230

text recognition

ocr20191230

Aliyun Java SDK OCR

ocr-20191230

product understanding

goodstech20191230

Aliyun Java SDK Goodstech

goodstech-20191230

content moderation

imageaudit20191230

Aliyun Java SDK Imageaudit

imageaudit-20191230

image recognition

imagerecog20190930

Aliyun Java SDK Imagerecog

imagerecog-20190930

image enhancement

imageenhan20190930

Aliyun Java SDK Imageenhan

imageenhan-20190930

image segmentation

imageseg20191230

Aliyun Java SDK Imageseg

imageseg-20191230

object detection

objectdet20191230

Aliyun Java SDK Objectdet

objectdet-20191230

visual search

imgsearch20200320

Aliyun Java SDK Imgsearch

imgsearch-20200320

image analysis and processing

imageprocess20200320

Aliyun Java SDK Imageprocess

imageprocess-20200320

video understanding

videorecog20200320

Aliyun Java SDK Videorecog

videorecog-20200320

video enhancement

videoenhan20200320

Aliyun Java SDK Videoenhan

videoenhan-20200320

video segmentation

videoseg20200320

Aliyun Java SDK Videoseg

videoseg-20200320

asynchronous task management

viapi20230117

Aliyun Java SDK Viapi

viapi-20230117

face verification server 20200910 dedicated version

facebody20200910

Aliyun Java SDK Facebody

facebody-20200910

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

    1. Copy the downloaded xxx.jar file and its dependencies to your project folder.

    2. In Eclipse, open your project, right-click the project, and then select Properties.

    3. In the dialog box that appears, click Java Build Path > Libraries > Add JARs to add the downloaded JAR file.

    4. Click Apply and Close.

  • Install in IntelliJ

    1. Copy the downloaded xxx.jar file and its dependencies to your project folder.

    2. In IntelliJ, open your project, right-click the xxx.jar file, and then select Add as Library.

    3. Click Apply, and then click OK.

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • 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

    1. Open a terminal in IntelliJ IDEA.

    2. 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_ID and ALIBABA_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.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. 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

Note

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:

  1. 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 ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage in your code.

  2. 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.NotFound error is returned. For more information about endpoints, see Endpoints.

  3. Use the Client class from the package of the corresponding service category.

  4. Use the Request and Response objects from the packages and classes of the corresponding service category.

  5. 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

Important

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:

  1. 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 ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage in your code.

  2. 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.NotFound error is returned. For more information about endpoints, see Endpoints.

  3. Use the Client class from the package of the corresponding service category.

  4. Use the Request and Response objects from the packages and classes of the corresponding service category.

  5. 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.