更新时间:2024-04-30 GMT+08:00
分享

开发前准备

本章节介绍了Java SDK的使用说明,您可以参考本章节进行快速集成开发。

开发前准备

  • 注册华为账号并开通华为云,已进行实名认证
  • 已具备开发环境 ,支持Java JDK 1.8及其以上版本。
  • 已获取账号对应的 Access Key(AK)和 Secret Access Key(SK)。请在控制台我的凭证 > 访问密钥页面上创建和查看您的 AK/SK。具体请参见访问密钥
  • 已获取转码服务对应区域的项目ID,请在控制台我的凭证 > API凭证页面上查看项目ID。具体请参见API凭证
  • 已将需要处理的媒资文件上传至MPC同区域的OBS桶中,并将OBS桶进行授权,允许MPC访问。具体请参见上传音视频文件获取云资源授权

Maven安装配置

下载settings.xml文件,覆盖<Maven安装目录>/conf/settings.xml文件即可。如果您不想覆盖配置文件,可以依次按照下面方法手动修改settings.xml文件。

  1. 在profiles节点中添加如下内容:
     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
    <profile>   
       <id>MyProfile</id>  
       <repositories>      
         <repository>         
           <id>HuaweiCloudSDK</id>          
           <url>https://repo.huaweicloud.com/repository/maven</url>          
         <releases>               
            <enabled>true</enabled>           
         </releases>           
         <snapshots>              
         <enabled>false</enabled>            
         </snapshots>       
         </repository>    
       </repositories>   
    
       <pluginRepositories>        
          <pluginRepository>            
             <id>HuaweiCloudSDK</id>           
             <url>https://repo.huaweicloud.com/repository/maven</url>          
             <releases>                
             <enabled>true</enabled>           
             </releases>          
             <snapshots>               
             <enabled>false</enabled>         
             </snapshots>      
           </pluginRepository>   
     </pluginRepositories>
    </profile>
    
  2. 在mirrors节点中增加:
    1
    2
    3
    4
    5
    <mirror>    
       <id>huaweicloud</id>   
       <mirrorOf>*,!HuaweiCloudSDK</mirrorOf>    
       <url>https://repo.huaweicloud.com/repository/maven</url>
    </mirror>
    
  3. 增加activeProfiles标签激活配置:
    1
    2
    3
    <activeProfiles>    
        <activeProfile>MyProfile</activeProfile>
    </activeProfiles>
    
  4. 配置pom.xml,添加媒体处理的SDK依赖,媒体处理服务具体的SDK版本号请参见SDK开发中心
    1
    2
    3
    4
    5
    <dependency>
        <groupId>com.huaweicloud.sdk</groupId>
        <artifactId>huaweicloud-sdk-mpc</artifactId>
        <version>3.0.39-rc</version>
    </dependency>
    

开始使用

  1. 导入依赖模块。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    // 用户身份认证
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    // 请求异常类
    import com.huaweicloud.sdk.core.exception.ClientRequestException;
    import com.huaweicloud.sdk.core.exception.ServerResponseException;
    // Http配置
    import com.huaweicloud.sdk.core.http.HttpConfig;
    // 导入mpc的客户端
    import com.huaweicloud.sdk.mpc.v1.MpcClient;
    // 导入待请求接口的request和response类
    import com.huaweicloud.sdk.mpc.v1.model.ListTranscodingTaskRequest;
    import com.huaweicloud.sdk.mpc.v1.model.ListTranscodingTaskResponse;
    // 日志打印
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    

  2. 配置客户端属性。

    1. 默认配置。
      1
      2
      // 使用默认配置
      HttpConfig config = HttpConfig.getDefaultHttpConfig();
      
    2. 代理配置(可选)。
      1
      2
      3
      4
      5
      6
      7
      // 使用代理服务器(可选)
      String userName = System.getenv("USER_NAME");
      String userPassword = System.getenv("USER_PASSWARD");
      config.withProxyHost("http://proxy.myhuaweicloud.com")
          .withProxyPort(8080)
          .withProxyUsername(userName)
          .withProxyPassword(userPassword);
      
    3. 连接配置(可选)。
      1
      2
      // 配置连接超时(可选)
      config.withTimeout(3);
      
    4. SSL配置(可选)。
      1
      2
      // 配置跳过服务端证书验证(可选)
      config.withIgnoreSSLVerification(true);
      

  3. 初始化认证信息。

    支持两种方式认证,您可以根据实际情况进行选择。

    • 使用永久AK/SK

      首先需要获取永久AK和SK,以及projectId,您可以参考开发前准备获取。

      1
      2
      3
      4
      5
      6
      7
      String ak = System.getenv("SDK_AK");
      String sk = System.getenv("SDK_SK");
      String projectId = System.getenv("PROJECT_ID");
      BasicCredentials credentials = new BasicCredentials()
          .withAk(ak)
          .withSk(sk)
          .withProjectId(projectId)
      
    • 使用临时AK/SK

      首先需要获取临时AK、SK和SecurityToken,您可以通过token获取或者通过委托授权获取

      1
      2
      3
      4
      5
      6
      7
      8
      9
      String ak = System.getenv("SDK_AK");
      String sk = System.getenv("SDK_SK");
      String projectId = System.getenv("PROJECT_ID");
      String securityToken = System.getenv("SECURITY_TOKEN");
      BasicCredentials credentials = new BasicCredentials()
              .withAk(ak)
              .withSk(sk)
              .withSecurityToken(securityToken)
              .withProjectId(projectId)
      
    相关参数说明如下所示:
    • ak:账号Access Key。
    • sk:账号Secret Access Key 。
    • projectId:云服务所在区域的项目ID ,根据您需要操作的项目所属区域选择对应的项目ID。
    • securityToken:采用临时AK/SK认证场景下的安全票据。

  4. 初始化客户端。

    1
    2
    3
    4
    5
    6
    //初始化MPC的客户端
    MpcClient MpcClient = MpcClient.newBuilder()
        .withHttpConfig(config)
        .withCredential(credentials)
        .withEndpoint(endpoint)
        .build();
    

    endpoint:MPC应用区域和各服务的终端节点,具体请参见地区和终端节点

  5. 发送请求并查看响应。

    1
    2
    3
    4
    5
    // 初始化请求,以调用查询转码模板接口为例
    ListTranscodingTaskResponse response = mpcClient.
    listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L))
    ));
    logger.info(response.toString());
    

  6. 异常处理。

    表1 异常处理

    一级分类

    一级分类说明

    二级分类

    二级分类说明

    ConnectionException

    连接类异常

    HostUnreachableException

    网络不可达、被拒绝

    SslHandShakeException

    SSL认证异常

    RequestTimeoutException

    响应超时异常

    CallTimeoutException

    单次请求,服务器处理超时未返回

    RetryOutageException

    在重试策略消耗完成已后,仍无有效的响应

    ServiceResponseException

    服务器响应异常

    ServerResponseException

    服务端内部错误,Http响应码:[500,]

    ClientRequestException

    请求参数不合法,Http响应码:[400, 500)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 异常处理
    try {
    ListTranscodingTaskResponse  response= mpcClient.listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)));
    } catch(ServiceResponseException e) {
        logger.error("HttpStatusCode: " + e.getHttpStatusCode());
        logger.error("RequestId: " + e.getRequestId());
        logger.error("ErrorCode: " + e.getErrorCode());
        logger.error("ErrorMsg: " + e.getErrorMsg());
    }
    

  7. 异步客户端使用。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    // 初始化异步客户端
    MpcAsyncClient mpcAsyncClient = 
    MpcAsyncClient.newBuilder()
        .withHttpConfig(config)
        .withCredential(credentials)
        .withEndpoint(endpoint)
        .build();
    
    // 发送异步请求
    CompletableFuture<ListTranscodingTaskResponse> future = mpcAsyncClient.listTranscodingTaskAsync(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)));
    
    // 获取异步请求结果
    ListTranscodingTaskResponse response = future.get();
    logger.info(response.toString());
    

  8. 访问日志。

    SDK在运行的时候采用了slf4j进行日志打印,如果在运行代码实例时,未配置日志实现库,会有提示如下:

    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.
    

    您可以根据目标项目实际情况引入对应的日志实现,请在对应的工程项目的pom.xml文件中引入日志实现的依赖,如下所示:

    • 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>
      

    SDK默认会打印访问日志,每次请求都会有一条记录,日志名称为"huaweiCloud-SDK-Access", 日志格式如下所示:

    "{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}

    其中“requestId”是APIG返回的请求ID,可以用于问题跟踪。

    可以根据项目情况在对应的日志配置文件中对访问日志进行屏蔽,或者单独打印到独立文件中。例如在logback中关闭访问日志:
    1
    <logger name="huaweiCloud-SDK-Access" level="OFF"> </logger>
    

  9. 原始HTTP侦听器。

    在某些场景下可能对业务发出的Http请求进行Debug,需要看到原始的Http请求和返回信息,SDK提供侦听器功能获取原始的和加密的Http请求和返回信息。

    原始信息打印仅在debug阶段使用,请不要在生产系统中将原始的Http头和Body信息打印到日志,这些信息并未加密且其中包含敏感数据;当Body体为二进制内容,即Content-Type标识为二进制时,body为"***",详细内容不输出。

     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 ->
        // 注册侦听器后打印Http Request 原始信息,请勿在生产系统中使用
        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 ->
        // 注册侦听器后打印Http Request 原始信息,请勿在生产系统中使用
        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(""))));
    
    MpcClient mpcClient = MpcClient.newBuilder()
        .withHttpConfig(config)
        .withCredential(auth)
        .withEndpoint(endpoint)
        .build();
    

代码示例 - 初始化MpcClient

Endpoint调用前请您根据实际情况填写,并替换如下变量:"SDK_AK"、"SDK_SK"、{your endpoint string}和{your project id}。
package com.huaweicloud.sdk.test;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.mpc.v1.MpcClient;

public class InitMpc {
    private static HttpConfig httpConfig;
    private static BasicCredentials auth;
    private static String endpoint;
    private static MpcClient mpcClient;

    public static MpcClient getMpcClient() {
        httpConfig = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true).withTimeout(3);
        //http代理设置,请根据实际情况设置
        //httpConfig.withProxyHost("xxxxx").withProxyPort(xxxxx).withProxyUsername("xxxxx").
        //        withProxyPassword("xxxxx");

        
        String ak = System.getenv("SDK_AK");
        String sk = System.getenv("SDK_SK");
        String projectId = System.getenv("PROJECT_ID");
        endpoint = "https://mpc.region01.myhuaweicloud.com";
        auth = new BasicCredentials().withAk(ak).withSk(sk).withProjectId(projectId);
        mpcClient = MpcClient.newBuilder()
                .withHttpConfig(httpConfig)
                .withCredential(auth)
                .withEndpoint(endpoint)
                .build();
        return mpcClient;
    }
}
分享:

    相关文档

    相关产品