All Products
Search
Document Center

Alibaba Cloud SDK:Java SDK FAQ

Last Updated:Jun 02, 2026

Common questions and solutions for integrating and using the Alibaba Cloud Java SDK.

Environment check

  • Java 1.8 or later is installed.

  • Your network can reach Alibaba Cloud API endpoints.

Common issues

AK parameter passing issues.

If your error message contains one of the following, the AccessKey is not configured correctly:

  • V2.0 SDK: Cannot invoke "com.aliyun.credentials.Client.getCredential()" because "this._credential" is null.

  • V1.0 SDK: ErrCode: MissingAccessKeyId. ErrMsg: AccessKeyId is mandatory for this action.

Solution:

  1. Verify that ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set:

    Linux/macOS

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

    Windows

    echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
    echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

    If the correct values are returned, the configuration is successful. Otherwise, reconfigure them as described in Configure environment variables on Linux, macOS, and Windows systems.

  2. Check your code for errors related to the AK.

    Common incorrect example:

    Config config = new Config()
             .setAccessKeyId(System.getenv("yourAccessKeyID"))   
             .setAccessKeySecret(System.getenv("yourSecret")); 

    Correct example:

    Config config = new Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    Note

    System.getenv() retrieves the AccessKey ID and Secret from your environment variables.

    Important

    Do not hardcode your AccessKey in online code. This practice poses a security risk.

unable to get credentials from any of the providers in the chain : ...

Cause: Your project uses the default credential provider (as shown below), but none of the supported credential types are configured.

com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
        .setCredential(credential);

Solution:

  • To use an AccessKey directly:

    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            // This example shows how to get the AccessKey ID from an environment variable.
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            // This example shows how to get the AccessKey secret from an environment variable.
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

    For other credential types, see Manage access credentials.

  • To continue using the default credential, you must configure any of the credential types supported by the default credential provider chain.

code 403, You are not authorized to do this operation. Action: xxxx.

image

The RAM user, role, or user group calling the API lacks the required permission. The Action:XXXX in the error message indicates the denied API operation. For example, Action:dysms:SendSms means the account lacks permission to call the SendSms API of Short Message Service.

Solution:

  1. Contact an administrator to create a custom permission policy based on the following document. Create a custom permission policy.

    Note

    This policy allows only SendSms calls to Short Message Service (dysms). Replace the Action with the service and API from your error message.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "dysms:SendSms",
          "Resource": "*"
        }
      ]
    }
  2. Grant permissions to the RAM account:

Error when importing Maven dependencies: Could not find artifact com.aliyun:XX:XX

Description:

Maven cannot find the specified dependency.

Solution:

Configure the Maven central repository in your project using one of the following methods:

  • Add the following content to the pom.xml file:

    <repositories>
        <repository>
            <id>central</id>
            <url>https://repo1.maven.org/maven2</url>
        </repository>
        <repository>
            <id>nexus-noke</id>
            <url>http://nexus.noke.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
  • Add the following content to the settings.xml file:

    <settings>
        <!-- Existing settings -->
        
        <mirrors>
            <mirror>
                <!-- This id can be any unique identifier -->
                <id>central</id>
                <mirrorOf>central</mirrorOf>
                <name>Maven Central Mirror</name>
                <url>https://repo1.maven.org/maven2</url>
            </mirror>
        </mirrors>
    </settings>

java: Error: release version X not supported.

In IntelliJ IDEA, press Ctrl+Alt+Shift+S to open Project Structure. Select Modules, then set Language Level to match your JDK version (for example, "8 - Lambdas, type annotations etc." for JDK 8). Click Apply, then OK.

image

java: Compilation failed: internal java compiler error.

In IntelliJ IDEA, go to File > Settings > Build, Execution, Deployment > Compiler > Java Compiler. Set both Project bytecode version and Target bytecode version to match your JDK version (for example, 8 for JDK 8). Click Apply, then OK.

image

code: 400, <CERTAIN_FIELD > is mandatory for this action.

A required parameter is missing in the API call. Solution:

Example using the SendSms API of Short Message Service:

  • Go to the API debugging page in the OpenAPI Portal, and select the cloud product and API.

  • Carefully compare the constructed request object, such as SendSmsRequest, to ensure all required fields, such as the phone number and signature, are filled.

  • Check the API documentation to confirm required parameters.

  • Ensure required parameter values are valid (for example, check that the phone number format is correct).

  • The SDK validates parameters before calling the API. If a required parameter is missing, you receive a MissingRequiredParameter error. For example, a missing phone number returns "MissingPhoneNumbers: code: 400".

image

SendSmsRequest sendSmsRequest = new SendSmsRequest()
        // Replace with the phone number that will receive the text message.
        .setPhoneNumbers("<YOUR_VALUE>")
        // Replace with your SMS signature.
        .setSignName("<YOUR_VALUE>")
        // Replace with your SMS template code.
        .setTemplateCode("<YOUR_VALUE>");

java.lang.NoSuchMethodError, java.lang.NoSuchFieldError

Cause:

This exception occurs when the Java runtime calls a method or accesses a field that does not exist. Common causes:

  • Outdated dependency version in your Maven pom.xml or Gradle build.gradle.

  • Dependency conflict: multiple versions of the same dependency exist, causing a lower version to load at runtime.

  • Stale cache: after updating a dependency, the project was not rebuilt or cache was not cleared.

  • Compile-time and runtime dependency versions differ.

  • Classpath conflict: The wrong classpath was selected during import.

Solution:

  1. Check the example provided in the Alibaba Cloud OpenAPI Portal to see if there is an error in the classpath.

  2. If the classpath is correct, you can obtain the specific class that caused the error from the exception stack information and find the corresponding dependency and version.

  3. Run the following command to view the direct and transitive dependencies of the project, along with specific conflicts and duplicates.

    • Maven: Maven uses "shortest path first" and "declaration order first" to resolve dependency versions. Resolve conflicts by adjusting the dependency order.

      mvn dependency:tree -Dverbose
    • Gradle: Gradle uses "highest version first" by default, so only outdated versions cause issues. Skip to step 4 to get the latest version.

  4. In the dependency tree output, check for conflicts. If found, move the highest version of the conflicting dependency to the top of the <dependencies></dependencies> section in pom.xml. Run mvn clean install -U to rebuild. If the error persists, continue below.

  5. Find the latest version of the dependency in V2.0 Java SDK common dependency packages. Update the version in your pom.xml or build.gradle.

  6. Clean and rebuild the project:

    • Maven

      mvn clean install -U
    • Gradle:

      gradle clean build --refresh-dependencies
  7. Verify that the issue is resolved.

Example:

The exception message is java.lang.NoSuchMethodError: com.aliyun.credentials.Client.getCredential().

  1. After checking, the classpath is correct.

  2. According to the exception message, the exception occurred in the com.aliyun.credentials.Client class, which is in the credentials-java dependency. The currently referenced version is 0.2.4.

  3. After running mvn dependency:tree -Dverbose, it is found that the parent dependency credentials-java, tea-openapi, has a version conflict. The currently referenced version is 0.3.2, and the conflicting version is 0.3.8. We recommend moving the parent dependency corresponding to version tea-openapi 0.3.8 to the top of the <dependencies></dependencies> section.

  4. Run the mvn clean install -U command to clean and rebuild the project, and verify that the issue is resolved.

  5. If the issue persists, you can obtain the latest version of credentials-java from Maven Central: com.aliyun:credentials-java and manually add the dependency to the pom.xml file.

"TeaUnretryableException: timeout", "java.net.SocketTimeoutException: connect timed out", "java.net.SocketTimeoutException: Read timed out", "SDK.ServerUnreachable", "Connection aborted", or "RemoteDisconnected".

Timeout issues have several common causes:

Network connectivity issues

The network between your client and the server is disconnected or unstable.

Solution:

Test connectivity to the cloud product endpoint using ping or curl. For example, if the SendSms API times out: ping dysmsapi.aliyuncs.com or curl -v https://dysmsapi.aliyuncs.com.

  • If the command times out, check for blocking policies in your firewall or router.

  • If the command succeeds, configure a reasonable timeout to avoid failures. See Timeout mechanism. Example:

// Runtime parameter timeout setting. This is effective only for requests that use this runtime parameter instance.
RuntimeOptions runtimeOptions = new RuntimeOptions();
runtimeOptions.connectTimeout = 5000;

Long API processing time

The API processing time exceeds the configured read timeout.

Solution: Increase the read timeout. See Timeout mechanism. Example:

// Runtime parameter timeout setting. This is effective only for requests that use this runtime parameter instance.
RuntimeOptions runtimeOptions = new RuntimeOptions();
runtimeOptions.readTimeout = 10000;

Your request is denied as lack of ssl protect.RequestId .

The API requires HTTPS, but your request used HTTP.

Solution:

  • For V1.0 SDK, set the HTTPS protocol on the Request object:

    request.setSysProtocol(com.aliyuncs.http.ProtocolType.HTTPS);
  • Use V2.0 SDK, which uses HTTPS by default.

code: 404, Specified api is not found, please check your url and method.

You entered an incorrect Endpoint or RegionId. Solution:

Verify that your region supports the target service. Find the product's Endpoint on its homepage in the OpenAPI Developer Portal. Example with Short Message Service:image

Unexpected response code for CONNECT: 400.

The request was intercepted by an intermediate node and did not reach the Alibaba Cloud gateway.

Solution:

  • The proxy configuration may be incorrect. Test with: curl https://<Alibaba Cloud service domain name>/ -v -x <proxy IP>:<proxy port> (for example, curl https://ecs-cn-hangzhou.aliyuncs.com/ -v -x 127.0.0.1:3128).

  • An internal firewall may be blocking the request. Try switching networks (for example, connect to a mobile hotspot).

Can not set java.lang.String field com.aliyun.imm20200930.models.GenerateWebofficeTokenShrinkRequest.userShrink to java.util .

An older version of the Tea package cannot convert a complex structure into a String, causing this error.

Solution:

Upgrade the Tea package to 1.2.7 or later:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>tea</artifactId>
  <version>1.2.7</version>
</dependency>

Failed to automatically download dependencies with Maven in IDEA.

  • Update the Maven repository

    Open the "File" menu and select "Settings" (or "Preferences"). In the navigation pane on the left, expand "Build, Execution, Deployment", and then select "Build Tools" > "Maven". Find the "Repositories" tab, select the local repository, click the "Update" button, and wait for the update to complete.tempsnip

  • Check the IDEA cache

    Open the "File" menu, select "Invalidate Caches...". In the dialog box that appears, select "Invalidate and Restart", and wait for IDEA to clear the cache and restart.

    image

  • Check the network connection

    If Maven cannot connect to the central repository or other remote repositories, it may not be able to download dependencies. Ensure your network connection is normal and that no firewalls or proxy servers are blocking Maven's access.

  • Check the Maven configuration

    Check that the Maven configuration file (usually settings.xml) is configured correctly. Ensure "localRepository" points to the correct local repository path, and that "mirrors", "proxies", and "profiles" are configured correctly.

How to avoid WARNING messages caused by reflection.

image.png

When using the Alibaba Cloud SDK with a higher JDK version, reflection-related warnings may appear in the output.

Solution:

Set the ALIBABA_CLOUD_SDK_LOG_LEVEL environment variable to ERROR to suppress warnings:

  1. Set the environment variable:

    Windows

    set ALIBABA_CLOUD_SDK_LOG_LEVEL=ERROR

    Linux/macOS

    export ALIBABA_CLOUD_SDK_LOG_LEVEL=ERROR
  2. Confirm the environment variable setting:

    Windows

    echo %ALIBABA_CLOUD_SDK_LOG_LEVEL%

    Linux/macOS

    echo $ALIBABA_CLOUD_SDK_LOG_LEVEL
  3. Start your application. Warning messages from the Alibaba Cloud SDK will no longer display; only ERROR-level or higher messages will appear.

Note
  • To change the log level for debugging or development, you can change the value of the environment variable to DEBUG or INFO.

Specified signature does not match our calculation.

image.png

The request signature does not match the server-side calculation. Possible causes:

  • AccessKey (AK) copied incorrectly

  • Incorrect signature algorithm

  • Request parameters or their order do not meet API requirements.

Solution:

  1. Verify that the AccessKey ID and Secret in your code exactly match those from the console (no extra spaces or special characters). Use an existing AccessKey or create a new one from Create an AccessKey pair. Note: The AccessKey Secret is shown only once at creation time.

  2. Upgrade commons-codec to avoid signature calculation errors:image.png

    Update the dependency:

    Maven

    Modify the pom.xml file.

    <dependency>
       <groupId>commons-codec</groupId>
       <artifactId>commons-codec</artifactId>
       <version>1.15</version> <!-- Updated version -->
    </dependency>

    After updating the version number, run the following command:

    mvn clean install

    Gradle

    In the build.gradle file, add or update the dependency:

    dependencies {
         implementation 'commons-codec:commons-codec:1.15' // Updated version
    }

    Run the following command to build the project:

    gradle build
  3. If using self-signing, verify that your code logic matches V3 request body & signature mechanism.

SDK.EndpointResolvingError: "No such region 'cn-XX'. Please check your region ID".

The SDK version is too old and does not support the target region or API. Solution:

Upgrade the SDK core dependency:

Maven

If you use Maven for project management, update the dependency version in the pom.xml file:

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

Gradle

If you use Gradle for project management, update the dependency version in the build.gradle file:

dependencies {
    implementation 'com.aliyun:aliyun-java-sdk-core:4.7.2'
    implementation 'com.aliyun:aliyun-java-sdk-sts:3.1.2'
}

Failed to instantiate [com.aliyuncs.IAcsClient]: Factory method 'iAcsClient' threw exception with message: org/apache/http/conn/ssl/DefaultHostnameVerifier .

An incompatible Apache HttpClient version is used with the Alibaba Cloud SDK. Solution:

  • Check that no other library introduces an incompatible HttpClient version using your build tool's dependency management.

  • Update Apache HttpClient to 4.5.14 or later:

    <dependency>
        <groupId>org.apache.httpcomponents.client</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.14</version> <!-- Please check for the latest version -->
    </dependency>

Error when calling an OpenAPI: code: 401, You have not activated the XXX service, or a similar message.

Your Alibaba Cloud account has not activated the corresponding service. XXX is the service name (for example, OCR service). Solution:

  1. Log on to the management console of the corresponding service.

  2. Find and enable the required feature.

  3. Wait for the service to be enabled and then call the API again.

Failed to get RAM session credentials from ECS metadata service. HttpCode=XX

The instance RAM role (ecs_ram_role) credential can only be used in an ECS or ECI instance with an attached RAM role. See ECS instance RAM role and Use an ECI instance RAM role by calling an API.

  • To verify this credential works, run the following command in the ECS instance:

    • Linux instance

      # Get the metadata access credential. You must set an expiration time. The request cannot contain the X-Forwarded-For header. 100.100.100.200 is the IPv4 address of the instance metadata service.
      TOKEN=`curl -X PUT "http://100.100.100.200/latest/api/token" -H "X-aliyun-ecs-metadata-token-ttl-seconds:<metadata_credential_expiration_time>"`
      # Access instance metadata
      curl -H "X-aliyun-ecs-metadata-token: $TOKEN" http://100.100.100.200/latest/meta-data/ram/security-credentials/[role-name]
    • Windows instance (PowerShell)

      # Get the metadata access credential. You must set an expiration time. The request cannot contain the X-Forwarded-For header. 100.100.100.200 is the IPv4 address of the instance metadata service.
      $token = Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token-ttl-seconds" = "<metadata_credential_expiration_time>"} -Method PUT -Uri http://100.100.100.200/latest/api/token
      # Access instance metadata
      Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token" = $token} -Method GET -Uri http://100.100.100.200/latest/meta-data/ram/security-credentials/[role-name]

    If the following response is returned, the instance RAM role credential is available:

    {
      "AccessKeyId" : "AccessKeyIdValue",
      "AccessKeySecret" : "AccessKeySecretValue",
      "Expiration" : "2025-07-10T08:37:58Z",
      "SecurityToken" : "SecurityTokenValue",
      "LastUpdated" : "2025-07-10T02:33:26Z",
      "Code" : "Success"
    }
  • To switch to a different credential type, see Manage access credentials.

There is a risk of leakage of this AccessKey

Cause: Your AccessKey may be at risk of leakage. Alibaba Cloud has applied protective restrictions.

Solution: Solutions for AccessKey leakage.

Request was denied due to api flow control

Cause: API calls are too frequent, triggering throttling (for example, "ThrottlingException").

Solution:

  • Implement a retry mechanism and increase the interval between requests to reduce load.

  • Optimize code logic: use batch processing or asynchronous calls to reduce request volume.

Specified access key denied due to access policy

Cause: An AccessKey network access restriction policy limits which source IP addresses can use a permanent AccessKey for API requests.

Solution:

  • Modify the IP address range in the AccessKey network access restriction policy.

  • Do not enable the AccessKey network access restriction policy.

AccessKey network access restriction policy.

com.aliyuncs.exceptions.ClientException: SDK.InvalidRegionId : Can not find endpoint to access

Cause: Incorrect parameters (such as an invalid regionId) prevent the SDK from finding the service endpoint.

Solution:

  • Verify that all configuration parameters (Endpoint, RegionId, etc.) are correct based on the Alibaba Cloud documentation and code examples.

  • Debug the API in the OpenAPI Developer Portal. After successful debugging, download the complete sample project for local use.

Basic Java exception checklist

Error message

Cause

Solution

NullPointerException

Tried to call a method or access a property on a null object.

Before using an object, perform a null check to avoid a NullPointerException. You can use a conditional statement or an assertion for the check.

ArrayIndexOutOfBoundsException

Tried to access an index that does not exist in the array.

Ensure the array index is within the valid range, which is greater than or equal to 0 and less than the array length. You can control loop conditions or manually check the index range to avoid an array-index out of bounds exception.

IllegalArgumentException

A method received an illegal argument.

Check the parameters passed to the method to ensure they meet the method's requirements. You can use a conditional statement or an assertion to check the validity of the parameters.

ArithmeticException

An exception occurred in an arithmetic operation, such as division by zero.

Before performing an arithmetic operation, perform the necessary checks and processing to ensure no exceptions will occur. You can use a conditional statement or an exception handling mechanism to handle arithmetic exceptions.

ClassCastException

Tried to cast an object to an incompatible type.

Before performing a type cast, use the instanceof operator to check the type and ensure the object's type is compatible. If the types are incompatible, consider using an appropriate type cast or redesigning the object's inheritance relationship.

FileNotFoundException

Tried to open a file that does not exist.

Ensure the file path and file name are correct, and that the file exists at the specified location. You can use a conditional statement or an exception handling mechanism to handle a file not found exception.

IOException

An exception occurred during an input/output operation, such as reading or writing a file, or network communication.

Check the correctness of the input/output operation, ensure the file or resource is available, and handle possible exceptions. You can use an exception handling mechanism to handle input/output exceptions.

InterruptedException

A thread was unexpectedly interrupted during a multi-threaded operation.

Handle thread interruptions appropriately when processing multi-threaded operations. You can use an exception handling mechanism or a conditional statement to handle thread interruption exceptions.

NoSuchMethodException

Tried to call a method that does not exist.

Check that the method name and parameters are correct, and ensure the method being called exists. You can use a conditional statement or an exception handling mechanism to handle a method not found exception.

NumberFormatException

Converted a string that cannot be converted to a number into a number.

When converting a string to a number, perform a reasonable check first to ensure the string can be correctly converted to a number. You can use a conditional statement or an exception handling mechanism to handle a number format exception.

IndexOutOfBoundsException

Tried to access an index that does not exist in a list or string.

Ensure the index is within the valid range, which is greater than or equal to 0 and less than the length of the list or string. You can use a conditional statement or an exception handling mechanism to handle an index out of bounds exception.

UnsupportedOperationException

Tried to call an unsupported method or operation.

Consult the documentation or API documentation to understand the supported methods and operations. Ensure the method or operation is feasible in the current environment.

IllegalMonitorStateException

Called the wait(), notify(), or notifyAll() method at an inappropriate time.

Ensure to use the wait(), notify(), or notifyAll() method correctly in a synchronized code block. You can use a conditional statement or an exception handling mechanism to handle an illegal monitor state exception.

SecurityException

Tried to perform an operation that violates security rules, such as unauthorized access or file permissions.

Check the security rules in the code to ensure they are not violated. You can make corresponding adjustments and modifications according to the security rules.

ClassNotFoundException

Tried to load a class that does not exist.

In the SDK, this is usually a dependency conflict, where multiple dependency versions coexist, causing the class loader to load the wrong version of the class. Check that the class name and classpath are correct, and ensure the required class exists. You can use a conditional statement or an exception handling mechanism to handle a class not found exception.

NoSuchFieldException

Tried to access a field that does not exist.

In the SDK, this is usually a dependency conflict, where a lower-version dependency has taken precedence in the index, causing the V2.0 SDK method to not exist. Ensure the field name is correct and that the field being accessed exists. You can use a conditional statement or an exception handling mechanism to handle a field not found exception.

Technical support

If you encounter other issues, contact us:

  • Submit a ticket: Alibaba Cloud Ticket Submission Page.

  • If you have related needs or feedback, you can add the DingTalk group to contact Alibaba Cloud technical support. The group number is 60965016010.