
# 开发前准备
本章节介绍了Java SDK的使用说明，您可以参考本章节进行快速集成开发。
 #### 开发前准备
- 已[注册](https://reg.huaweicloud.com/registerui/public/custom/register.html#/register)华为账号并开通华为云，已进行[实名认证](https://support.huaweicloud.com/usermanual-account/account_auth_00001.html)。
- 已具备开发环境 ，支持Java JDK 1.8及其以上版本。
- 已获取账号对应的 Access Key（AK）和 Secret Access Key（SK）。请在控制台"我的凭证 \> 访问密钥"页面上创建和查看您的 AK/SK。具体请参见[访问密钥](https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html)。
- 已获取转码服务对应区域的项目ID，请在控制台"我的凭证 \> API凭证"页面上查看项目ID。具体请参见[API凭证](https://support.huaweicloud.com/usermanual-ca/ca_01_0002.html)。
- 已将需要处理的媒资文件上传至MPC同区域的OBS桶中，并将OBS桶进行授权，允许MPC访问。具体请参见[上传音视频文件](https://support.huaweicloud.com/usermanual-mpc/mpc010002.html)和[获取云资源授权](https://support.huaweicloud.com/usermanual-mpc/mpc010003.html)。
- 媒体处理的SDK版本号详见[SDK开发中心](https://sdkcenter.developer.huaweicloud.com/)。
 
#### Maven安装配置
[下载](https://mirrors.huaweicloud.com/v1/configurations/maven_huaweicloudsdk?)settings.xml文件，覆盖\<Maven安装目录\>/conf/settings.xml文件即可。如果您不想覆盖配置文件，可以依次按照下面方法手动修改settings.xml文件。
1. 在profiles节点中添加如下内容：
   ```
   <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节点中增加：
   ```
   <mirror>    
      <id>huaweicloud</id>   
      <mirrorOf>*,!HuaweiCloudSDK</mirrorOf>    
      <url>https://repo.huaweicloud.com/repository/maven</url>
   </mirror>
   ```
   
3. 增加activeProfiles标签激活配置：
   ```
   <activeProfiles>    
       <activeProfile>MyProfile</activeProfile>
   </activeProfiles>
   ```
   
4. 在pom.xml文件中引入媒体处理SDK，详见[表1]。
   ```
   <dependency>
       <groupId>com.huaweicloud.sdk</groupId>
       <artifactId>huaweicloud-sdk-mpc</artifactId>
       <version>3.1.88</version>
   </dependency>
   ```
    表1媒体处理SDK的依赖 
   | 依赖名称                                           | 版本     |
   |:---|:---|
   | com.huaweicloud.sdk:huaweicloud-sdk-core       | 3.1.88 |
   | org.yaml:snakeyaml                             | 2.0    |
   | com.fasterxml.jackson.core:jackson-core        | 2.14.2 |
   | com.fasterxml.jackson.core:jackson-annotations | 2.14.2 |
   | com.fasterxml.jackson.core:jackson-databind    | 2.14.2 |
      
   
 
#### 开始使用
1. 导入依赖模块。 
   ```
   // 用户身份认证
   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. 默认配置。
      ```
      // 使用默认配置
      HttpConfig config = HttpConfig.getDefaultHttpConfig();
      ```
      
   
   2. 代理配置（可选）。
      ```
      // 使用代理服务器（可选）
      String userName = System.getenv("USER_NAME");
      String userPassword = System.getenv("USER_PASSWORD");
      config.withProxyHost("http://proxy.myhuaweicloud.com")
          .withProxyPort(8080)
          .withProxyUsername(userName)
          .withProxyPassword(userPassword);
      ```
      
   
   3. 连接配置（可选）。
      ```
      // 配置连接超时（可选）
      config.withTimeout(3);
      ```
      
   
   4. SSL配置（可选）。
      ```
      // 配置跳过服务端证书验证（可选）
      config.withIgnoreSSLVerification(true);
      ```
      
   
   
   
   
3. 初始化认证信息。 
   支持两种方式认证，您可以根据实际情况进行选择。
   - 使用永久AK/SK 首先需要获取永久AK和SK，以及projectId，您可以参考[开发前准备]获取。
     ```
     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获取](https://support.huaweicloud.com/api-iam/iam_04_0002.html)或者[通过委托授权获取](https://support.huaweicloud.com/api-iam/iam_04_0101.html)。
     ```
     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. 初始化客户端。 
   ```
   //初始化MPC的客户端
   MpcClient MpcClient = MpcClient.newBuilder()
       .withHttpConfig(config)
       .withCredential(credentials)
       .withEndpoint(endpoint)
       .build();
   ```
   **endpoint：** MPC应用区域和各服务的终端节点，具体请参见[地区和终端节点](https://developer.huaweicloud.com/endpoint?MPC)。
   
   
5. 发送请求并查看响应。 
   ```
   // 初始化请求，以调用查询转码模板接口为例
   ListTranscodingTaskResponse response = mpcClient.
   listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L))
   ));
   logger.info(response.toString());
   ```
   
   
6. 异常处理。 
   表2异常处理 
   | 一级分类                     | 一级分类说明  | 二级分类                     | 二级分类说明                      |
   |:---|:---|:---|:---|
   | ConnectionException      | 连接类异常   | HostUnreachableException | 网络不可达、被拒绝                   |
   | ConnectionException      | 连接类异常   | SslHandShakeException    | SSL认证异常                     |
   | RequestTimeoutException  | 响应超时异常  | CallTimeoutException     | 单次请求，服务器处理超时未返回             |
   | RequestTimeoutException  | 响应超时异常  | RetryOutageException     | 在重试策略消耗完成以后，仍无有效的响应         |
   | ServiceResponseException | 服务器响应异常 | ServerResponseException  | 服务端内部错误，Http响应码：\[500,\]    |
   | ServiceResponseException | 服务器响应异常 | ClientRequestException   | 请求参数不合法，Http响应码：\[400， 500) |
      
   ```
   // 异常处理
   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. 异步客户端使用。 
   ```
   // 初始化异步客户端
   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进行日志打印，如果在运行代码实例时，未配置日志实现库，会有提示如下：
   ```
   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
     ```
     <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
     ```
     <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中关闭访问日志：
   ```
   <logger name="huaweiCloud-SDK-Access" level="OFF"> </logger>
   ```
   
   
9. 原始HTTP侦听器。 
   在某些场景下可能对业务发出的Http请求进行Debug，需要看到原始的Http请求和返回信息，SDK提供侦听器功能获取原始的和加密的Http请求和返回信息。
   ![](https://support.huaweicloud.com/sdkreference-mpc/public_sys-resources/caution_3.0-zh-cn.png)
   原始信息打印仅在debug阶段使用，请不要在生产系统中将原始的Http头和Body信息打印到日志，这些信息并未加密且其中包含敏感数据；当Body体为二进制内容，即Content-Type标识为二进制时，body为"\*\*\*"，详细内容不输出。
   ```
   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;
    }
}
```
