SecretId
and SecretKey
. SecretId
is used to identify the API requester, while SecretKey
is a key used for signature string encryption and authentication by the server. You can get them on the API Key Management page as shown below:Note:Your security credential represents your account identity and granted permissions, which is equivalent to your login password. Do not disclose it to others.
*.tencentcloudapi.com
and varies by service. For example, the endpoint of CVM is cvm.tencentcloudapi.com
. For specific endpoints, please see the API documentation of the corresponding service.Maven is a dependency management tool for Java that supports the dependencies your project requires and installs them into your project.
<dependencies>
tag in Maven's pom.xml
. You can find the latest version (v3.1.322) in the Maven repository.<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<!-- go to https://search.maven.org/search?q=tencentcloud-sdk-java and get the latest version. -->
<!-- Please query the latest version at https://search.maven.org/search?q=tencentcloud-sdk-java, which is as follows -->
<version>3.1.322</version>
</dependency>
Note:
- The version number here is just an example, and you can view the latest version number in the Maven repository.
- v4.0.11 shown in the Maven repository was disused but has not been completely deleted due to the Maven index update issue.
- The above import method downloads the SDKs of all Tencent Cloud products to your local system. You can replace the
artifactId
with a specific product SDK name such astencentcloud-sdk-java-cvm/cbs/vpc
to import the SDK of the specific product. The code can be used in the same way, and the major packages are the same. For more information, please see the samples. The latest version can also be queried in the Maven repository, which can greatly save the storage space.
- Set the mirror source to speed up the download. To do so, edit the
settings.xml
configuration file of Maven and add the mirror configuration in themirrors
section:
<mirror>
<id>tencent</id>
<name>tencent maven mirror</name>
<url>https://mirrors.tencent.com/nexus/repository/maven-public/</url>
<mirrorOf>*</mirrorOf>
</mirror>
vendor
directory in a path that can be found by Java.The following uses the instance querying API DescribeInstances
as an example:
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.cvm.v20170312.CvmClient;
import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesRequest;
import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse;
public class DescribeInstances {
public static void main(String[] args) {
try {
Credential cred = new Credential("secretId", "secretKey");
CvmClient client = new CvmClient(cred, "ap-shanghai");
DescribeInstancesRequest req = new DescribeInstancesRequest();
DescribeInstancesResponse resp = client.DescribeInstances(req);
System.out.println(DescribeInstancesResponse.toJsonString(resp));
} catch (TencentCloudSDKException e) {
System.out.println(e.toString());
}
}
}
You can find more detailed samples in the examples
directory on the GitHub page.
Starting from v3.0.96, an HTTP proxy can be set separately:
HttpProfile httpProfile = new HttpProfile();
httpProfile.setProxyHost("real proxy IP");
httpProfile.setProxyPort(real proxy port);
Starting from v3.1.16, we add the support for the common parameter Language
to meet the globalization requirements of certain products. As before, Language
is not passed in by default subject to the decisions of each service API, which is usually Chinese but can also be English by default in some products. Currently, valid values are Chinese and English, which can be set in the following way:
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.Language;
...
ClientProfile clientProfile = new ClientProfile();
clientProfile.setLanguage(Language.ZH_CN);
The SDK supports both HTTP and HTTPS protocols, and the switch between protocols can be implemented by setting the setProtocol()
method in HttpProfile
:
HttpProfile httpProfile = new HttpProfile();
httpProfile.setProtocol("http://"); // HTTP protocol
httpProfile.setProtocol("https://"); // HTTPS protocol
Starting from v3.1.80, the SDK supports printing logs.
First, when creating the ClientProfile
object, set the debug
mode to true, and the SDK exception information and traffic information will be printed.
ClientProfile clientProfile = new ClientProfile();
clientProfile.setDebug(true);
Tencent Cloud SDK for Java uses the commons.logging
class to print logs as shown below:
September 10, 2020 5:14:30 PM com.tencentcloudapi.cvm.v20170312.CvmClient info
Information: send request, request url: https://cvm.ap-shanghai.tencentcloudapi.com/?Nonce=367595572&Action=DescribeInstances&Filters.0.Values.1=ap-shanghai-2&Version=2017-03-12&Filters.0.Values.0=ap-shanghai-1&SecretId=AKIDziAMHwiVO0LPCizu61e1iCQP7YiaOX7Q&Filters.0.Name=zone&RequestClient=SDK_JAVA_3.1.129&Region=ap-shanghai&SignatureMethod=HmacSHA256&Timestamp=1599729270&Signature=DcGRPdquMZZRPj1NFXP5bsOGnRlaT2KXy7aegNhZa00%3D. request headers information:
September 10, 2020 5:14:32 PM com.tencentcloudapi.cvm.v20170312.CvmClient info
Information: recieve response, response url: https://cvm.ap-shanghai.tencentcloudapi.com/?Nonce=367595572&Action=DescribeInstances&Filters.0.Values.1=ap-shanghai-2&Version=2017-03-12&Filters.0.Values.0=ap-shanghai-1&SecretId=AKIDziAMHwiVO0LPCizu61e1iCQP7YiaOX7Q&Filters.0.Name=zone&RequestClient=SDK_JAVA_3.1.129&Region=ap-shanghai&SignatureMethod=HmacSHA256&Timestamp=1599729270&Signature=DcGRPdquMZZRPj1NFXP5bsOGnRlaT2KXy7aegNhZa00%3D, response headers: Server: nginx;Date: Thu, 10 Sep 2020 09:14:32 GMT;Content-Type: application/json;Content-Length: 103;Connection: keep-alive;OkHttp-Selected-Protocol: http/1.1;OkHttp-Sent-Millis: 1599729271230;OkHttp-Received-Millis: 1599729272020;,response body information: com.squareup.okhttp.internal.http.RealResponseBody@8646db9
You can configure the log printout class as needed, such as log4j
, in the following way:
pom
file and set the log4j
version. <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
log4j
and create a log class.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
Log logger = LogFactory.getLog("TestLog");
logger.info("hello world");
We recommend you use the new version of SDK. If you need a legacy version, add the following dependencies to your Maven's pom.xml
:
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>qcloud-java-sdk</artifactId>
<version>2.0.6</version>
</dependency>
Please note that upgrading from v3.0.x to 3.1.x causes compatibility issues. As integer
fields have been modified to long
type, the project needs to be recompiled.
Currently, the SDK depends on OkHttp 2.5.0. If it is mixed with other packages that depend on OkHttp 3, an error may be reported, such as Exception in thread "main" java.lang.NoSuchMethodError: okio.BufferedSource.rangeEquals(JLokio/ByteString;)Z
. The reason is that OkHttp 3 depends on Okio 1.12.0, while OkHttp 2.5.0 depends on Okio 1.6.0. When Maven parses dependencies, it gives top priority to the shortest path in sequence, so if the SDK is declared in the pom.xml dependency first, Okio 1.6.0 will be used, and an error will be reported.
Solution before the SDK is upgraded to OkHttp 3:
Note:There may be other packages that require a higher version, in which case, take the highest compatible version as a workaround; for example, when other packages use OkHttp 4, the corresponding version may be Okio 2.2.2.
<dependency>
<groupId>com.squareup.okio</groupId>
<artifactId>okio</artifactId>
<version>1.12.0</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cmq-http-client</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.59</version>
</dependency>
Certificate issues are usually caused by incorrect configuration of the client environment. The SDK does not manipulate the certificate and relies on the processing by the Java runtime environment itself. After a certificate issue occurs, you can run -Djavax.net.debug=ssl
to enable detailed logs for troubleshooting.
Some users reported that the certificate error javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
occurred while using IBM JDK 1.8. The error was resolved after Oracle JDK was used.
Starting from v3.1.303, Tencent Cloud SDK for Java supports the use of Common Client
mode for requests. You only need to install the Common
package to initiate calls to any Tencent Cloud product.
Note:You must clearly know the parameters required by the called API; otherwise, the call may fail.
Currently, only the POST method is supported, and the signature algorithm must be signature algorithm v3. For detailed usage, please see the Using Common Client to Call sample.
Starting from v3.1.310, Tencent Cloud SDK for Java supports request retry. For each request, you can set the number of retries between 0 and 10. If an API request fails, it will be retried at intervals of 1s until it succeeds or the number of retries is used up.
For detailed usage, please see the Using retry
to Retry Request sample.
Tencent Cloud SDK for Java currently supports the following methods for credential management:
By default, the environment variables TENCENTCLOUD_SECRET_ID
and TENCENTCLOUD_SECRET_KEY
are read to get secretId
and secretKey
. The relevant code is as follows:
Credential cred = new EnvironmentVariableCredentialsProvider().getCredentials();
The configuration file path should be as follows:
c:\Users\NAME\.tencentcloud\credentials
~/.tencentcloud/credentials
or /etc/tencentcloud/credentials
The configuration file is in the following format:
[default]
secret_id = xxxxx
secret_key = xxxxx
The relevant code is as follows:
Credential cred = new ProfileCredentialsProvider().getCredentials();
For related concepts of role assumption, please see Role Overview.
To use this method, you must create a role in the Tencent Cloud CAM console as instructed in Creating a Role.
After you have a role, you can get temporary credentials through the persistent key and roleArn
, and the SDK will automatically refresh the temporary credentials. The relevant code is as follows:
Credential cred = new STSCredential("secretId", "secretKey", "roleArn", "roleSessionName");
For related concepts of instance role, please see Managing Roles.
After you bind a role to an instance, you can access the relevant metadata APIs on the instance to get temporary credentials, and the SDK will automatically refresh the temporary credentials. The relevant code is as follows:
Credential cred = new CvmRoleCredential();
Tencent Cloud SDK for Java provides a credential supply chain. By default, it will try to get credentials in the order of environment variable -> configuration file -> instance role and return the first obtained credential. The relevant code is as follows:
Credential cred = new DefaultCredentialsProvider().getCredentials();
For detailed usage of credential management, please see the Using Credential Supply Chain sample.
Was this page helpful?