JAVA

更新时间:
复制 MD 格式

This document provides Java code examples.

Installation

The following are the pom dependencies:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.5.13</version>
</dependency>

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-alinlp</artifactId>
  <version>1.8.14</version>
</dependency>

Configure access credentials using environment variables

  1. Note:

    1. An AccessKey for an Alibaba Cloud account grants access permissions to all APIs and poses a high security risk. We recommend that you create and use a Resource Access Management (RAM) user for API access or daily operations and maintenance (O&M). To create a RAM user, log on to the RAM console.

    2. Do not save your AccessKey ID and AccessKey secret in your code. This practice can lead to the leakage of your AccessKey pair. This document demonstrates how to save and access your credentials by configuring environment variables.

  2. Configuration for Linux and macOS

    export NLP_AK_ENV=<access_key_id>
    export NLP_SK_ENV=<access_key_secret>

    Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey secret. For more information about how to obtain an AccessKey ID and an AccessKey secret, see Step 2: Obtain an AccessKey for your account.

  3. Windows configuration method

    1. Create the NLP_AK_ENV and NLP_SK_ENV environment variables. Set the value of NLP_AK_ENV to your AccessKey ID and the value of NLP_SK_ENV to your AccessKey secret.

    2. Restart Windows.

Call using the AliNLP 2.0 method (Recommended)

The following code shows an example of how to call the part-of-speech tagging algorithm. To call other algorithms, see the Change the API request section and replace the `actionName` and request parameters in the code.

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;

import com.aliyuncs.alinlp.model.v20200629.GetPosChEcomRequest;
import com.aliyuncs.alinlp.model.v20200629.GetPosChEcomResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

public class TestCloud {
    /**
     * Code example: Call the part-of-speech tagging algorithm
     */
    public static void main(String[] args) throws ClientException {
        /**
         * An AccessKey for an Alibaba Cloud account has access permissions for all APIs, which poses a high security risk. Create and use a RAM user for API access or daily O&M. Log on to the RAM console to create a RAM user.
         * This example shows how to store the AccessKey ID and AccessKey secret in environment variables. You can also store them in a configuration file as needed.
         * Do not save your AccessKey ID and AccessKey secret in your code. This practice can lead to key leakage.
         */
        String accessKeyId = System.getenv("NLP_AK_ENV");
        String accessKeySecret = System.getenv("NLP_SK_ENV");
        DefaultProfile defaultProfile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,
                accessKeySecret);
        IAcsClient client = new DefaultAcsClient(defaultProfile);
        // Construct the request. GetPosChEcom is the algorithm's actionName. Replace it with the actionName of your target algorithm from the API Reference. For an example, see the "Change the API request" section.
        GetPosChEcomRequest request = new GetPosChEcomRequest();
        // Static field. Do not change.
        request.setSysEndpoint("alinlp.cn-hangzhou.aliyuncs.com");
        // Static field. Do not change.
        request.setServiceCode("alinlp");
        // Request parameters. See the API Reference for details.
        request.setText("This is a text.");
        request.setTokenizerId("MAINSE");
        long start = System.currentTimeMillis();
        // Get the request result. Note that GetPosChEcom must also be replaced here.
        GetPosChEcomResponse response = client.getAcsResponse(request);
        System.out.println(response.hashCode());
        System.out.println(response.getRequestId() + "\n" + response.getData() + "\n" + "cost:" + (System.currentTimeMillis()- start));
    }
}

Change the API request

The class names, such as GetPosChEcomRequest (request parameter class) and GetPosChEcomResponse (response class), contain the `actionName` of the algorithm. In this example, the `actionName` is GetPosChEcom. To call a different algorithm, replace GetPosChEcom with the `actionName` of that algorithm. You can find the `actionName` in the corresponding API Reference document under Request Parameters > Action > Example Value.

For example, to call Basic Edition - Chinese Word Segmentation - General, refer to Chinese Word Segmentation (Basic Edition) and copy the example value shown in the following figure. Then, replace GetPosChEcomRequest with GetWsChGeneralRequest and GetPosChEcomResponse with GetWsChGeneralResponse. After you replace the class names, you must also change the request parameters for the algorithm as described in the API documentation.

Call using the Common Request method

Common Requests Document

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;

public class AliNLP2 {
    public static void main(String[] args) {
      	/**
         * An AccessKey for an Alibaba Cloud account has access permissions for all APIs, which poses a high security risk. Create and use a RAM user for API access or daily O&M. Log on to the RAM console to create a RAM user.
         * This example shows how to store the AccessKey ID and AccessKey secret in environment variables. You can also store them in a configuration file as needed.
         * Do not save your AccessKey ID and AccessKey secret in your code. This practice can lead to key leakage.
         */
        String accessKeyId = System.getenv("NLP_AK_ENV");
        String accessKeySecret = System.getenv("NLP_SK_ENV");
        DefaultProfile defaultProfile = DefaultProfile.getProfile(
                "cn-hangzhou",
                accessKeyId,
                accessKeySecret);
        IAcsClient client = new DefaultAcsClient(defaultProfile);
        // Create an API request and set the parameters.
        CommonRequest request = new CommonRequest();
        // The domain and version are static fields.
        request.setDomain("alinlp.cn-hangzhou.aliyuncs.com");
        request.setVersion("2020-06-29");
        // The action name is available in the API documentation.
        request.setSysAction("GetPosChEcom");
        // The parameters for put are available in the API documentation.
        request.putQueryParameter("ServiceCode", "alinlp");
        request.putQueryParameter("Text", "This is a text.");
        request.putQueryParameter("TokenizerId", "MAINSE");

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Troubleshoot call exceptions

If an exception occurs during a call, see Troubleshoot call exceptions (error code summary). Find the error code in the document to identify the cause of the error and the solution.