Java SDK User Guide
This section describes how to quickly integrate the Java SDK for development.
Prerequisites
- You have registered with Huawei Cloud and completed real-name authentication.
If you are a user of Huawei Cloud (International) or Huawei Cloud (Europe), you need to complete real-name authentication when you:
- Purchase and use cloud services in Huawei Cloud regions in the Chinese mainland. In this case, real-name authentication is required by the laws and regulations of the Chinese mainland.
- Plan to use Live in Huawei Cloud regions in the Chinese mainland.
- You have obtained and added an ingest domain name and a streaming domain name (both licensed) on the Live console, and associated the domain names.
- The development environment (Java JDK 1.8 or later) is available.
- You have obtained the access key (AK) and secret access key (SK) of the Huawei Cloud account. You can create and view your AK and SK on the My Credentials > Access Keys page of the Huawei Cloud console. For details, see Access Keys.
- You have obtained the project ID of the corresponding region of Live. You can view the project ID on the API Credentials. page of the Huawei Cloud console. For details, see
Notes
When the version of the introduced third-party library conflicts with the version of the third-party library on which the Live service depends, for example, the version conflict of Jackson or OkHttp3, the following bundle package (later than 3.0.40-rc) can be introduced to redirect the version of the third-party library on which the SDK depends to resolve the version conflict. For details, see SDK Center to check the SDK bundle package of the Java SDK of Live.
Note: The bundle package contains the core package and cloud service collection package. Therefore, you do not need to introduce the core package and service package separately. Otherwise, the bundle package may not take effect based on the parsing sequence of Maven dependencies.
<dependency> <groupId>com.huaweicloud.sdk</groupId> <artifactId>huaweicloud-sdk-bundle</artifactId> <version>${version}</version> </dependency>
Installing an SDK
You can obtain and install an SDK in Maven mode. You need to download and install Maven in your operating system (OS). After the installation is complete, you only need to add the corresponding dependencies to the pom.xml file of the Java project.
Replace the value of version in the following sample code with the actual SDK version.
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>com.huaweicloud.sdk</groupId> <artifactId>huaweicloud-sdk-core</artifactId> <version>3.1.11</version> </dependency> <dependency> <groupId>com.huaweicloud.sdk</groupId> <artifactId>huaweicloud-sdk-live</artifactId> <version>3.1.11</version> </dependency> |
Procedure
- Import the dependent module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Perform user authentication. import com.huaweicloud.sdk.core.auth.BasicCredentials; // Import a request exception class. import com.huaweicloud.sdk.core.exception.ClientRequestException; import com.huaweicloud.sdk.core.exception.ServerResponseException; // Configure HTTP. import com.huaweicloud.sdk.core.http.HttpConfig; // Import a Live client. import com.huaweicloud.sdk.live.v1.LiveClient; // Import the request and response classes of an API. import com.huaweicloud.sdk.live.v1.model.ShowTranscodingsTemplateRequest; import com.huaweicloud.sdk.live.v1.model.ShowTranscodingsTemplateResponse; // Print logs. import org.slf4j.Logger; import org.slf4j.LoggerFactory;
- Configure client attributes.
- Use the default configuration.
1 2
// Use the default configuration. HttpConfig config = HttpConfig.getDefaultHttpConfig();
- (Optional) Configure a proxy.
1 2 3 4 5 6 7
// (Optional) Use a proxy server. // There will be huge security risks if the password of the proxy server is directly written into the code. You are advised to store the password in ciphertext in the configuration file or environment variables and decrypt the password when using it. // Before configuring a proxy, specify the environment variable PROXY_PASSWORD in the local environment. config.withProxyHost("http://proxy.huaweicloud.com") .withProxyPort(8080) .withProxyUsername("test") .withProxyPassword(System.getenv("PROXY_PASSWORD"));
- (Optional) Configure a connection.
1 2
// (Optional) Configure connection timeout. config.withTimeout(3);
- (Optional) Configure SSL.
1 2
// (Optional) Skip server certificate verification. config.withIgnoreSSLVerification(true);
- Use the default configuration.
- Initialize authentication information.
You can use one of the following two authentication modes:
- Permanent AK and SK
Obtain a permanent AK, SK and project ID. For details, see Prerequisites.
1 2 3 4
BasicCredentials credentials = new BasicCredentials() .withAk(ak) .withSk(sk) .withProjectId(projectId)
- Temporary AK and SK
Obtain a temporary AK, SK, and security token through a token or through an agency.
1 2 3 4 5
BasicCredentials credentials = new BasicCredentials() .withAk(ak) .withSk(sk) .withSecurityToken(securityToken) .withProjectId(projectId)
The related parameters are as follows:- ak: AK of the Huawei Cloud account. You are advised to store the AK in ciphertext in the configuration file or environment variables and decrypt it when using it.
- sk: SK of the Huawei Cloud account. You are advised to store the SK in ciphertext in the configuration file or environment variables and decrypt it when using it.
- projectId: ID of the project where Live is provided. Select a project ID based on the region of the project.
- securityToken: security token used for temporary AK and SK authentication
- Permanent AK and SK
- Initialize the client.
1 2 3 4 5 6
// Initialize the Live client. LiveClient liveClient = LiveClient.newBuilder() .withHttpConfig(config) .withCredential(credentials) .withRegion(region) .build();
region: regions where Live is used and endpoints of each service.
- Send a request and view the response.
1 2 3 4 5
// Initialize the request. The following uses the API for querying transcoding templates as an example. ShowTranscodingsTemplateResponse showTranscodingsTemplateResponse = liveClient.showTranscodingsTemplate( new ShowTranscodingsTemplateRequest().withDomain(domain) // domain indicates the domain name to be queried. ); logger.info(showTranscodingsTemplateResponse.toString());
- Perform troubleshooting.
Table 1 Troubleshooting Level 1
Description
Level 2
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).
1 2 3 4 5 6 7 8 9 10 11
// Perform troubleshooting. try { ShowTranscodingsTemplateResponse showTranscodingsTemplateResponse = liveClient.showTranscodingsTemplate( new ShowTranscodingsTemplateRequest().withDomain("play.example.huaweicloud.com") ); } catch(ServiceResponseException e) { logger.error("HttpStatusCode: " + e.getHttpStatusCode()); logger.error("RequestId: " + e.getRequestId()); logger.error("ErrorCode: " + e.getErrorCode()); logger.error("ErrorMsg: " + e.getErrorMsg()); }
- Use an asynchronous client.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Initialize an asynchronous client. LiveAPIAsyncClient liveAsyncClient = LiveAPIAsyncClient.newBuilder() .withHttpConfig(config) .withCredential(credentials) .withRegion(region) .build(); // Send an asynchronous request. CompletableFuture<ShowTranscodingsTemplateResponse> future = LiveAPIAsyncClient.showTranscodingsTemplate( new ShowTranscodingsTemplateRequest().withDomain("play.example.huaweicloud.com") ); // Obtain the asynchronous response. showTranscodingsTemplateResponse response = future.get(); logger.info(response.toString());
- Print access logs.
The running SDK uses Simple Logging Facade for Java (SLF4J) to print logs. If the logging library is not configured when the code instance is run, the following information is displayed:
1 2 3
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
You can introduce the logging library dependencies to the pom.xml file of the target project, as shown in the following examples.
- SLF4J
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.21</version> </dependency> logback <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency>
- log4j
1 2 3 4 5
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
By default, the SDK prints access logs. Each request has a record named HuaweiCloud-SDK-Access. The log format is as follows:
"{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}
requestId indicates the request ID returned by Huawei Cloud API Gateway, which can be used for issue tracking.
You can disable access logs in the corresponding log configuration file or record access logs in an independent file. For example, you can disable access logs in the Logback framework by adding the following configuration:1
<logger name="HuaweiCloud-SDK-Access" level="OFF"> </logger>
- SLF4J
- Use the listener to obtain original HTTP requests and responses.
The original HTTP requests and responses are required for debugging HTTP requests sent by the service side. The SDK provides the listener to obtain the original and encrypted HTTP requests and responses.
Original information is printed only during debugging. Do not print the header and body of an original HTTP request in the production system because this information contains sensitive data but is not encrypted. If the request body is binary, that is, Content-Type is set to binary, the body will be displayed as *** without the detailed content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
HttpConfig config = new HttpConfig().addHttpListener(HttpListener.forRequestListener(requestListener -> // After the listener is registered, the original information about the HTTP requests is printed. Do not print the original information in the production system. logger.debug("REQUEST: {} {} {} {}", requestListener.httpMethod(), requestListener.uri(), requestListener.headers().entrySet().stream().flatMap(entry -> entry.getValue().stream().map(value -> entry.getKey() + " : " + value)) .collect(Collectors.joining(";")), requestListener.body().orElse("")))); .addHttpListener(HttpListener.forResponseListener(responseListener -> // After the listener is registered, the original information about the HTTP requests is printed. Do not print the original information in the production system. logger.debug("RESPONSE: {} {} {} {} {}", responseListener.httpMethod(), responseListener.uri(), responseListener.statusCode(), responseListener.headers().entrySet().stream().flatMap(entry -> entry.getValue().stream().map(value -> entry.getKey() + " : " + value)) .collect(Collectors.joining(";")), responseListener.body().orElse("")))); LiveClient liveClient = LiveClient.newBuilder() .withHttpConfig(config) .withCredential(auth) .withRegion(region) .build();
Sample Code
Before the calling, replace the variables {your endpoint string} and {your project id} as needed.
There will be huge security risks if the AK and SK used for authentication are directly written into the code. You are advised to store the AK and SK in ciphertext in the configuration file or environment variables and decrypt them when using them.
In this example, the AK and SK are stored in environment variables. Before running this example, specify the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package com.huaweicloud.sdk.test; // Perform user authentication. import com.huaweicloud.sdk.core.auth.BasicCredentials; // Import a request exception class. import com.huaweicloud.sdk.core.exception.ClientRequestException; import com.huaweicloud.sdk.core.exception.ServerResponseException; // Configure HTTP. import com.huaweicloud.sdk.core.http.HttpConfig; // Import the Live client. import com.huaweicloud.sdk.live.v1.LiveClient; // Import the request and response classes of an API. import com.huaweicloud.sdk.live.v1.model.ShowTranscodingsTemplateRequest; import com.huaweicloud.sdk.live.v1.model.ShowTranscodingsTemplateResponse; // Print logs. import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void showTranscodingsTemplate(LiveClient client) { try { // Initialize the request. The following uses the API for querying transcoding templates as an example. ShowTranscodingsTemplateResponse showTranscodingsTemplateResponse = client.showTranscodingsTemplate( new ShowTranscodingsTemplateRequest().withDomain("play.example.huaweicloud.com") ); // Output the response in JSON. logger.info(showTranscodingsTemplateResponse.toString()); } catch (ClientRequestException e) { logger.error("HttpStatusCode: " + e.getHttpStatusCode()); logger.error("RequestId: " + e.getRequestId()); logger.error("ErrorCode: " + e.getErrorCode()); logger.error("ErrorMsg: " + e.getErrorMsg()); } } public static void main(String[] args) { String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); String endpoint = "{your endpoint string}"; String projectId = "{your project id}"; // Configure client attributes. HttpConfig config = HttpConfig.getDefaultHttpConfig(); config.withIgnoreSSLVerification(true); // Create a credential. BasicCredentials auth = new BasicCredentials() .withAk(ak) .withSk(sk) .withProjectId(projectId); // Create and initialize a Live client instance. LiveClient liveClient = LiveClient.newBuilder() .withHttpConfig(config) .withCredential(auth) .withRegion(region) .build(); showTranscodingsTemplate(liveClient); } } |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.