Updated on 2024-06-13 GMT+08:00

Java SDK

This section describes how to use the new Java SDK to quickly develop OCR services.

Prerequisites

  • You have registered a Huawei ID and enabled Huawei Cloud services. Your account cannot be in arrears or frozen.
  • Java JDK 1.8 or later is available.
  • You have obtained an AK and an SK on the My Credentials > Access Keys page. The AK and SK are contained in the credentials.csv file.
    Figure 1 Creating an access key

  • You have obtained the IAM user name, account name, and the project ID of your target region on the My Credentials > API Credentials page. The information will be used during service calling. Save it in advance.
    Figure 2 API Credentials

Installing the SDK

Obtain and install the SDK using Maven. Download and install Maven in your operating system. Add the dependency to the pom.xml file of the Java project.

Before using the SDK, install huaweicloud-sdk-core and huaweicloud-sdk-ocr. Obtain the latest version of the SDK package from SDK Center and replace the version in the code.

<dependency>
    <groupId>com.huaweicloud.sdk</groupId>
    <artifactId>huaweicloud-sdk-core</artifactId>
    <version>3.1.5</version>
</dependency>
<dependency>
    <groupId>com.huaweicloud.sdk</groupId>
    <artifactId>huaweicloud-sdk-ocr</artifactId>
    <version>3.1.5</version>
</dependency>

When a third-party library conflict occurs, for example, a Jackson or OkHttp3 version conflict, you can import the following bundle package (version later than 3.0.40-rc). This package contains all supported services and redirected third-party software on which the SDK depends to avoid conflicts with the libraries on which the service depends.

<dependency>
    <groupId>com.huaweicloud.sdk</groupId>
    <artifactId>huaweicloud-sdk-bundle</artifactId>
    <version>[3.0.40-rc, 3.1.0)</version>
</dependency>

For details about the Jackson version requirements, see pom.xml.

Getting Started

  1. Import dependency modules.
    package com.huaweicloud.sdk.test;
    import com.huaweicloud.sdk.core.auth.ICredential;
    // Authenticate the user.
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    // Import a request exception class.
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    // Import the OCR client.
    import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
    import com.huaweicloud.sdk.ocr.v1.*;
    import com.huaweicloud.sdk.ocr.v1.model.*;
  2. Configure client connection parameters.
    • Using the default configuration
      // Use the default configuration.
      HttpConfig config = HttpConfig.getDefaultHttpConfig();
    • (Optional) Configuring a network proxy
      // Configure a network proxy as needed. The default protocol of the network proxy is HTTP.
      config.withProxyHost("proxy.huaweicloud.com")
          .withProxyPort(8080)
          .withProxyUsername("test")
          .withProxyPassword("test");
    • (Optional) Configuring the timeout
      // The default connection timeout interval is 60 seconds. You can change it as needed.
      config.withTimeout(60);
    • (Optional) Configuring an SSL
      // Configure whether to skip SSL certificate verification as needed.
      // If the "javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure" error is reported during SDK execution, add the following code to skip SSL certificate verification:
      config.withIgnoreSSLVerification(true);
  3. Configure authentication information.

    Configure ak, sk, and project_id. AK is used together with SK to sign requests cryptographically, ensuring that the requests are secret, complete, and correct. There are two authentication methods:

    • Initialize authentication information.
      String ak = System.getenv("HUAWEICLOUD_SDK_AK");
      String sk = System.getenv("HUAWEICLOUD_SDK_SK");
      • Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
      • In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
      • If environment variables are not set, you can skip calling the System.getenv method and directly enter the corresponding ak and sk values, for example, String ak = "ak"; String sk = "sk".
    • Using a permanent AK and SK
      BasicCredentials basicCredentials = new BasicCredentials()
          .withAk(ak)
          .withSk(sk)
          .withProjectId(projectId);
    • Using a temporary AK and SK
      BasicCredentials basicCredentials = new BasicCredentials()
          .withAk(ak)
          .withSk(sk)
          .withSecurityToken(securityToken)
          .withProjectId(projectId)

    The authentication parameters are described as follows:

    • ak and sk: access key and secrete access key. For details about how to obtain them, see Prerequisites.
    • projectId: Huawei Cloud project ID. For details about how to obtain the ID, see Prerequisites.
    • securityToken: security token used for temporary AK/SK authentication. It can be obtained through a token or an agency.
  4. Initialize the client (using either of the following methods).
    • (Recommended) Specifying a region
      // Add the region dependency.
      import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
      
      // Initialize the client authentication information. If the current client is used, projectId or domainId can be left blank.
      ICredential auth = new BasicCredentials()
          .withAk(ak)
          .withSk(sk);
      // Initialize the client {Service}Client of a specified cloud service. The following uses OcrClient of OCR as an example.
      OcrClient Client = OcrClient.newBuilder()
          .withHttpConfig(config)
          .withCredential(auth)
          .withRegion(OcrRegion.valueOf("ap-southeast-2"))
          .build();
    • Specifying an endpoint for a cloud service
      // Specify the endpoint for OCR, for example, AP-Bangkok.
      String endpoint = "https://ocr.ap-southeast-2.myhuaweicloud.com";
      // Initialize the client authentication information. You need to configure projectId or domainId. The following uses BasicCredentials as an example.
      BasicCredentials basicCredentials = new BasicCredentials()
          .withAk(ak)
          .withSk(sk)
          .withProjectId(projectId);
      
      // Initialize the client {Service}Client of a specified cloud service. The following uses OcrClient of a region-level OCR as an example.
      OcrClient ocrClient = OcrClient.newBuilder()
          .withHttpConfig(config)
          .withCredential(basicCredentials)
          .withEndpoint(endpoint)
          .build();

      endpoint indicates the endpoints for Huawei Cloud services. For details, see Regions and Endpoints.

  5. Send a request and check the response.
    // The following uses calling the RecognizePassport API of Passport OCR as an example.
    RecognizePassportRequest request = new RecognizePassportRequest();
    PassportRequestBody body = new PassportRequestBody();
    body.withUrl("Image URL");
    request.withBody(body);
    try {
        RecognizePassportResponse response = client.recognizePassport(request);
        System.out.println(response.toString());
    } catch (ConnectionException e) {
        e.printStackTrace();
    } catch (RequestTimeoutException e) {
        e.printStackTrace();
    } catch (ServiceResponseException e) {
        e.printStackTrace();
        System.out.println(e.getHttpStatusCode());
        System.out.println(e.getErrorCode());
        System.out.println(e.getErrorMsg());
    }
  6. Handle the exception.
    Table 1 Exception handling

    Level-1 Category

    Level-1 Category Description

    Level-2 Category

    Level-2 Category Description

    ConnectionException

    Connection exception

    HostUnreachableException

    The network is unreachable or access is rejected.

    SslHandShakeException

    SSL authentication is abnormal.

    RequestTimeoutException

    Response timeout exception

    CallTimeoutException

    The server fails to respond to a single request before timeout.

    RetryOutageException

    No valid response is returned after the maximum number of retries specified in the retry policy is reached.

    ServiceResponseException

    Server response exception

    ServerResponseException

    Internal server error. HTTP response code: [500,].

    ClientRequestException

    Invalid request parameter. HTTP response code: [400, 500).

    // Troubleshooting
    try {
        RecognizePassportResponse response = client.recognizePassport(request);
        System.out.println(response.toString());
    } catch (ConnectionException e) {
        e.printStackTrace();
    } catch (RequestTimeoutException e) {
        e.printStackTrace();
    } catch (ServiceResponseException e) {
        e.printStackTrace();
        System.out.println(e.getHttpStatusCode());
        System.out.println(e.getErrorCode());
        System.out.println(e.getErrorMsg());
    }

For details about how to use the asynchronous client and configure logs, see SDK Center and Java SDK Usage Guide.

Automatic Generation of Sample Code

API Explorer allows for API search and platform debugging, with features such as quick and comprehensive search, visual debugging, access to help documentation, and online consultation.

You only need to modify API parameters in the API Explorer to automatically generate the corresponding sample code.

Figure 3 API Explorer