Java SDK example

Updated at:

This topic shows how to call the liveness face detection API by using the Java SDK.

SDK usage

If you need SDK example code in other languages, you can debug APIs in OpenAPI Explorer. This online tool automatically generates SDK call example code for the corresponding API. You can click the following API links to debug:

Debug the LivenessFaceVerify API

This example uses the latest Java SDK. For earlier versions, see LivenessFaceVerify: Silent face liveness detection.

Prerequisites

Java 1.8 or later.

Maven dependency

<dependency>
 <groupId>com.aliyun</groupId>
 <artifactId>cloudauth20190307</artifactId>
 <version>2.0.8</version>
</dependency>

Example

Important

The code examples demonstrate basic API calls and are for illustration only. For production use, optimize and refactor the code to meet your business requirements.

For example, to improve performance, we recommend implementing the singleton pattern for generic objects such as credentialClient, config, and client. The code examples include comments recommending this practice.

import com.aliyun.cloudauth20190307.Client;
import com.aliyun.cloudauth20190307.models.LivenessFaceVerifyRequest;
import com.aliyun.cloudauth20190307.models.LivenessFaceVerifyResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.Arrays;
import java.util.List;

public class LivenessFaceVerify {

    // Use the singleton pattern to improve performance.
    private static com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();

    public static void main(String[] args) throws Exception {

        // Create an API request and set the parameters.
        LivenessFaceVerifyRequest request = new LivenessFaceVerifyRequest();
        // Enter your scene ID.
        request.setSceneId(0L);
        request.setOuterOrderNo("A unique identifier for the merchant request");
        request.setProductCode("LR_FR_MIN");
        // The card authentication type. This is a fixed value.
        request.setModel("FRONT_CAMERA_LIVENESS");
        //request.setDeviceToken("xxxx");
        //request.setMobile("130xxxxxxxx");
        //request.setIp("114.xxx.xxx.xxx");
        //request.setUserId("12345xxxx");
        // Select one of the following methods to provide the face image.
        // Method 1: Provide the Base64-encoded face image.
        request.setFaceContrastPicture("The Base64-encoded face image");
        // Method 2: Provide the OSS bucket name and object name.
        //request.setOssBucketName("cn-shanghai-aliyun-cloudauth-xxxxx");
        //request.setOssObjectName("verify/xxxxx/xxxxxx.jpeg");
        // Method 3: Provide the OSS URL of the face image, which must be accessible over the public network.
        //request.setFaceContrastPictureUrl("https://cn-shanghai-aliyun-cloudauth-xxxxxx.oss-cn-shanghai.aliyuncs.com/verify/xxxxx/xxxxx.jpeg");

        // Recommended. Supports service routing.
        LivenessFaceVerifyResponse response = livenessFaceVerifyAutoRoute(request);

        // Does not support automatic service routing.
        //LivenessFaceVerifyResponse response = livenessFaceVerify("cloudauth.cn-shanghai.aliyuncs.com", request);

        System.out.println(response.getBody().getRequestId());
        System.out.println(response.getBody().getCode());
        System.out.println(response.getBody().getMessage());
        System.out.println(response.getBody().getResultObject() == null ? null
                : response.getBody().getResultObject().getPassed());
        System.out.println(response.getBody().getResultObject() == null ? null
                : response.getBody().getResultObject().getSubCode());
        System.out.println(response.getBody().getResultObject() == null ? null
                : response.getBody().getResultObject().getMaterialInfo());
    }

    private static LivenessFaceVerifyResponse livenessFaceVerifyAutoRoute(LivenessFaceVerifyRequest request) {
        // The first endpoint is the primary endpoint, and the second is the backup endpoint.
        List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
        LivenessFaceVerifyResponse lastResponse = null;
        for (int i=0; i<endpoints.size(); i++) {
            try {
                LivenessFaceVerifyResponse response = livenessFaceVerify(endpoints.get(i), request);
                lastResponse = response;

                // If a server-side error occurs, try the next endpoint.
                if(response != null){
                    if(500 == response.getStatusCode()){
                        continue;
                    }
                    if(response.getBody() != null){
                        if("500".equals(response.getBody().getCode())){
                            continue;
                        }
                    }
                }

                return response;
            } catch (Exception e) {
                e.printStackTrace();
                if(i == endpoints.size()-1){
                    throw new RuntimeException(e);
                }
            }
        }

        return lastResponse;
    }

    private static LivenessFaceVerifyResponse livenessFaceVerify(String endpoint, LivenessFaceVerifyRequest request)
            throws Exception {
        // An AccessKey pair from an Alibaba Cloud account grants full API permissions. For better security, we recommend that you use a RAM user to call API operations or perform routine O&M.
        // To prevent security risks, do not hard-code your AccessKey ID and AccessKey Secret in your code.
        // This example uses the Alibaba Cloud Credentials tool to read the AccessKey pair from environment variables for identity verification. For more information about configuring environment variables, see https://help.aliyun.com/document_detail/378657.html.
        // We recommend that you use the singleton pattern.
        Config config = new Config();
        config.setCredential(credentialClient);
        config.setEndpoint(endpoint);
        // Set an HTTPS proxy.
        //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
        // Set an HTTP proxy.
        //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
        
        // We recommend that you use the singleton pattern.
        Client client = new Client(config);

        // Create a RuntimeOptions instance and set runtime parameters.
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        return client.livenessFaceVerifyWithOptions(request, runtime);
    }
}