
# Java SDK
本章节介绍人脸识别服务Java SDK，您可以参考本章节进行快速集成开发。
 #### 准备工作
- [注册华为账号并开通华为云](https://support.huaweicloud.com/usermanual-account/account_id_001.html)，并完成实名认证，账号不能处于欠费或冻结状态。
- 已开通人脸识别服务。如未开通，请登录[人脸识别管理控制台](https://console.huaweicloud.com/frs/)开通所需服务。
- 已具备开发环境，支持Java JDK 1.8 及其以上版本。
- 登录"[我的凭证](https://console.huaweicloud.com/iam/#/myCredential) \> 访问密钥"页面，获取Access Key（AK）和Secret Access Key（SK）。
  图1获取AK、SK   
  ![](https://support.huaweicloud.com/sdkreference-face/zh-cn_image_0000001732074588.png "点击放大") 
- 登录"[我的凭证](https://console.huaweicloud.com/iam/#/myCredential)"页面，获取"IAM用户名"、"账号名"以及待使用区域的"项目ID"。调用服务时会用到这些信息，请提前保存。
  本样例以"华北-北京四"区域为例，获取对应的项目ID（project_id）。
  图2我的凭证   
  ![](https://support.huaweicloud.com/sdkreference-face/zh-cn_image_0000001732363634.png "点击放大") 
 
#### 安装SDK
推荐您通过Maven方式获取和安装SDK，首先需要在您的操作系统中[下载](https://maven.apache.org/download.cgi)并[安装Maven](https://maven.apache.org/install.html)，安装完成后您只需要在Java项目的pom.xml文件中加入相应的依赖项即可。
使用SDK前，需要安装"huaweicloud-sdk-core"和"huaweicloud-sdk-frs"依赖项。请在[SDK中心](https://sdkcenter.developer.huaweicloud.com/?language=java)获取最新的sdk包版本，替换代码中版本。
```
<dependency>
    <groupId>com.huaweicloud.sdk</groupId>
    <artifactId>huaweicloud-sdk-core</artifactId>
    <version>3.1.12</version>
</dependency>
<dependency>
    <groupId>com.huaweicloud.sdk</groupId>
    <artifactId>huaweicloud-sdk-frs</artifactId>
    <version>3.1.12</version>
</dependency>
```
![](https://support.huaweicloud.com/sdkreference-face/public_sys-resources/note_3.0-zh-cn.png)
当出现第三方库冲突的时，如Jackson，okhttp3版本冲突等。可以引入如下bundle包(3.0.40-rc版本后)，该包包含所有支持的服务和重定向了SDK依赖的第三方软件，避免和业务自身依赖的库产生冲突：
```
<dependency>
    <groupId>com.huaweicloud.sdk</groupId>
    <artifactId>huaweicloud-sdk-bundle</artifactId>
    <version>[3.0.40-rc, 3.1.0)</version>
</dependency>
```
jackson版本要求请见[pom.xml](https://github.com/huaweicloud/huaweicloud-sdk-java-v3/blob/master/pom.xml)。SDK常见报错请参考[代码运行报错]、[json解析报错]。
#### 开始使用
在开始使用之前，请确保您安装的是最新版本的SDK。使用过时的版本可能会导致兼容性问题或无法使用最新功能。您可以通过运行以下命令来检查SDK版本，并在[SDK中心](https://sdkcenter.developer.huaweicloud.com/?language=java)获取最新的SDK包版本。
```
mvn dependency:tree | grep huaweicloud-sdk-core
mvn dependency:tree | grep huaweicloud-sdk-frs
```
详细的SDK介绍，使用异步客户端，配置日志等操作请参见[SDK中心](https://sdkcenter.developer.huaweicloud.com/)、[Java SDK使用指导](https://github.com/huaweicloud/huaweicloud-sdk-java-v3/blob/master/README_CN.md)、[Java SDK使用视频](https://res-video.hc-cdn.com/cloudbu-site/china/zh-cn/support/sdk-video/1620783979754083351.mp4)。
1. 导入依赖模块
   ```
   import com.huaweicloud.sdk.core.auth.ICredential;
   import com.huaweicloud.sdk.core.auth.BasicCredentials;
   import com.huaweicloud.sdk.core.exception.ConnectionException;
   import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
   import com.huaweicloud.sdk.core.exception.ServiceResponseException;
   //导入v2版本sdk
   import com.huaweicloud.sdk.frs.v2.region.FrsRegion;
   import com.huaweicloud.sdk.frs.v2.*;
   import com.huaweicloud.sdk.frs.v2.model.*;
   ```
   
2. 配置认证信息
   配置AK、SK信息。华为云通过AK识别用户的身份，通过SK对请求数据进行签名验证，用于确保请求的机密性、完整性和请求者身份的正确性。AK、SK获取方法请参见[准备工作]。
   ```
   public static ICredential getCredential(String ak, String sk) {
       return new BasicCredentials()
               .withAk(ak)
               .withSk(sk);
   }
   ```
   初始化认证信息：
   ```
   String ak = System.getenv("HUAWEICLOUD_SDK_AK");
   String sk = System.getenv("HUAWEICLOUD_SDK_SK");
   ICredential credential = getCredential(ak, sk);
   ```
   ![](https://support.huaweicloud.com/sdkreference-face/public_sys-resources/caution_3.0-zh-cn.png)
   - 认证用的 ak 和sk 硬编码到代码中或者明文存储都有很大的安全风险，建议在配置文件或者环境变量中密文存放，使用时解密，确保安全。
   
   - 本示例以 ak 和 sk 保存在环境变量中来实现身份验证为例，运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。
    
   图3Windows环境新建环境变量   
   ![](https://support.huaweicloud.com/sdkreference-face/zh-cn_image_0000001779029181.png "点击放大") 
3. 初始化客户端
   指定region方式
   ```
   public static FrsClient getClient(Region region, ICredential auth) {
       // 初始化人脸识别服务的客户端
       FrsClient client = FrsClient.newBuilder()
               .withCredential(auth)
               .withRegion(FrsRegion.valueOf("cn-north-4")) // 选择服务所在区域 FrsRegion.valueOf("cn-north-4")
               .build();
       return client;
   }
   ```
   服务部署区域请参见[终端节点](https://support.huaweicloud.com/api-face/face_02_0057.html)。
   
4. 发送请求并查看响应
   ```
   // 以调用人脸检测 DetectFaceByBase64 接口为例
   DetectFaceByBase64Request request = new DetectFaceByBase64Request();
   FaceDetectBase64Req body = new FaceDetectBase64Req();
   body.withImageBase64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
   request.withBody(body);
   DetectFaceByBase64Response response = client.detectFaceByBase64(request);
   System.out.println(response.toString());
   ```
   ![](https://support.huaweicloud.com/sdkreference-face/public_sys-resources/note_3.0-zh-cn.png)
   使用人脸比对SDK时，image1、image2参数需为相同类型，即同为url、base64或file。
   
5. 异常处理
   表1异常处理 
   | 一级分类                     | 一级分类说明  | 二级分类                     | 二级分类说明                      |
   |:---|:---|:---|:---|
   | ConnectionException      | 连接类异常   | HostUnreachableException | 网络不可达、被拒绝。                  |
   | ConnectionException      | 连接类异常   | SslHandShakeException    | SSL认证异常。                    |
   | RequestTimeoutException  | 响应超时异常  | CallTimeoutException     | 单次请求，服务器处理超时未返回。            |
   | RequestTimeoutException  | 响应超时异常  | RetryOutageException     | 在重试策略消耗完成后，仍无有效的响应。         |
   | ServiceResponseException | 服务器响应异常 | ServerResponseException  | 服务端内部错误，Http响应码：\[500,\]。   |
   | ServiceResponseException | 服务器响应异常 | ClientRequestException   | 请求参数不合法，Http响应码：\[400, 500) |
      
   ```
   // 捕获和处理不同类型的异常
   DetectFaceByBase64Request request = new DetectFaceByBase64Request();
   try {
       DetectFaceByBase64Response response = client.detectFaceByBase64(request);
       System.out.println(response.toString());
   } catch (ConnectionException e) {
       e.printStackTrace();
   } catch (RequestTimeoutException e) {
       e.printStackTrace();
   } catch (ServiceResponseException e) {
       e.printStackTrace();
       System.out.println(e.getHttpStatusCode());
       System.out.println(e.getErrorCode());
       System.out.println(e.getErrorMsg());
   }
   ```
   
 
#### SDK demo 代码解析
- 人脸检测
  ```
  // detect face by base64
  DetectFaceByBase64Request detectRequest = new DetectFaceByBase64Request();
  FaceDetectBase64Req faceDetectBase64Req = new FaceDetectBase64Req();
  faceDetectBase64Req.withImageBase64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
  faceDetectBase64Req.withAttributes("2");
  detectRequest.setBody(faceDetectBase64Req);
  try {
      DetectFaceByBase64Response detectResponse = client.detectFaceByBase64(detectRequest);
      System.out.println(detectResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  // detect face by file
  File file = new File("/root/picture.jpg");
  DetectFaceByFileRequest byFileRequest = new DetectFaceByFileRequest();
  DetectFaceByFileRequestBody requestBody = new DetectFaceByFileRequestBody();
  try (InputStream inputStream = Files.newInputStream(file.toPath())){
      requestBody.withImageFile(inputStream, file.getName());
      byFileRequest.setBody(requestBody);
      DetectFaceByFileResponse response = client.detectFaceByFile(byFileRequest);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  } catch (IOException e) {
      e.printStackTrace();
  }
  ```
  
- 人脸比对
  ```
  // compare face by base64
  CompareFaceByBase64Request compareRequest = new CompareFaceByBase64Request();
  FaceCompareBase64Req faceCompareBase64Req = new FaceCompareBase64Req();
  faceCompareBase64Req.withImage1Base64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
  faceCompareBase64Req.withImage2Base64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
  compareRequest.withBody(faceCompareBase64Req);
  try {
      CompareFaceByBase64Response compareResponse = client.compareFaceByBase64(compareRequest);
      System.out.println(compareResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  // compare face by file
  ```
  ```
  File file1 = new File("/root/picture1.jpg");
  File file2 = new File("/root/picture2.jpg");
  try (InputStream inputStream1 = Files.newInputStream(file1.toPath());
      InputStream inputStream2 = Files.newInputStream(file2.toPath())) {
      CompareFaceByFileRequest request = new CompareFaceByFileRequest();
      CompareFaceByFileRequestBody requestBody = new CompareFaceByFileRequestBody();
      requestBody.withImage1File(inputStream1, file1.getName());
      requestBody.withImage2File(inputStream2, file2.getName());
      request.setBody(requestBody);
      CompareFaceByFileResponse response = client.compareFaceByFile(request);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  } catch (IOException e) {
      e.printStackTrace();
  }
  ```
  
- 人脸搜索
  ```
  // search face by base64
  SearchFaceByBase64Request searchRequest = new SearchFaceByBase64Request();
  searchRequest.withFaceSetName("face_set_name");
  FaceSearchBase64Req faceSearchBase64Req = new FaceSearchBase64Req();
  List<Map<String, String>> listbodySort = new ArrayList<>();
  Map<String, String> map = new HashMap<>();
  map.put("timestamp","asc");
  listbodySort.add(map);
  List<String> listbodyReturnFields = new ArrayList<>();
  listbodyReturnFields.add("timestamp");
  listbodyReturnFields.add("id");
  faceSearchBase64Req.withSort(listbodySort);
  faceSearchBase64Req.withReturnFields(listbodyReturnFields);
  faceSearchBase64Req.withImageBase64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
  searchRequest.withBody(faceSearchBase64Req);
  try {
      SearchFaceByBase64Response searchResponse = client.searchFaceByBase64(searchRequest);
      System.out.println(searchResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  // search face by file
  SearchFaceByFileRequest byFileRequest = new SearchFaceByFileRequest();
  byFileRequest.withFaceSetName("face_set_name");
  File file = new File("/root/picture.jpg");
  try (InputStream inputStream = Files.newInputStream(file.toPath())) {
      SearchFaceByFileRequestBody fileRequestBody = new SearchFaceByFileRequestBody();
      fileRequestBody.withImageFile(inputStream, file.getName());
      byFileRequest.withBody(fileRequestBody);
      fileRequestBody.withSort("[{ \"timestamp\": \"desc\"}]");
      fileRequestBody.withReturnFields("[\"timestamp\"]");
      SearchFaceByFileResponse fileResponse = client.searchFaceByFile(byFileRequest);
      System.out.println(fileResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  } catch (IOException e) {
      e.printStackTrace();
  }
  ```
  
- 创建人脸库
  ```
  CreateFaceSetRequest createFaceSetRequest = new CreateFaceSetRequest();
  CreateFaceSetReq createFaceSetReq = new CreateFaceSetReq();
  createFaceSetReq.withFaceSetName("face_set_name");
  Map<String, TypeInfo> stringTypeInfoMap = new HashMap<>();
  TypeInfo typeInfo = new TypeInfo();
  typeInfo.withType("long");
  stringTypeInfoMap.put("timestamp", typeInfo);
  createFaceSetReq.withExternalFields(stringTypeInfoMap);
  createFaceSetRequest.withBody(createFaceSetReq);
  try {
      CreateFaceSetResponse createFaceSetResponse = client.createFaceSet(createFaceSetRequest);
      System.out.println(createFaceSetResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 查询人脸库
  ```
  ShowFaceSetRequest showFaceSetRequest = new ShowFaceSetRequest();
  showFaceSetRequest.withFaceSetName("face_set_name");
  try {
      ShowFaceSetResponse showFaceSetResponse = client.showFaceSet(showFaceSetRequest);
      System.out.println(showFaceSetResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 查询所有人脸库
  ```
  ShowAllFaceSetsRequest showAllFaceSetsRequest = new ShowAllFaceSetsRequest();
  try {
      ShowAllFaceSetsResponse showAllFaceSetsResponse = client.showAllFaceSets(showAllFaceSetsRequest);
      System.out.println(showAllFaceSetsResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 删除人脸库
  ```
  DeleteFaceSetRequest deleteFaceSetRequest = new DeleteFaceSetRequest();
  deleteFaceSetRequest.withFaceSetName("face_set_name");
  try {
      DeleteFaceSetResponse deleteFaceSetResponse = client.deleteFaceSet(deleteFaceSetRequest);
      System.out.println(deleteFaceSetResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 添加人脸
  ```
  //add face by base64
  AddFacesByBase64Request addFacesByBase64Request = new AddFacesByBase64Request();
  addFacesByBase64Request.withFaceSetName("face_set_name");
  AddFacesBase64Req addFacesBase64Req = new AddFacesBase64Req();
  addFacesBase64Req.withExternalFields("{\"timestamp\":12}");
  addFacesBase64Req.withImageBase64("9j/4AAQSkZJRgABAQAAAQABAAD...");
  addFacesByBase64Request.withBody(addFacesBase64Req);
  try {
      AddFacesByBase64Response addFacesByBase64Response = client.addFacesByBase64(addFacesByBase64Request);
      System.out.println(addFacesByBase64Response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  //add face by file
  AddFacesByFileRequest fileRequest = new AddFacesByFileRequest();
  fileRequest.withFaceSetName("face_set_name");
  AddFacesByFileRequestBody fileRequestBody = new AddFacesByFileRequestBody();
  File file = new File("/root/picture.jpg");
  try (InputStream inputStream = Files.newInputStream(file.toPath())) {
      fileRequestBody.withImageFile(inputStream, file.getName());
      fileRequestBody.setExternalFields("{\"id\": \"zhangsan\"}");
      fileRequest.withBody(fileRequestBody);
      AddFacesByFileResponse fileResponse = client.addFacesByFile(fileRequest);
      System.out.println(fileResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  } catch (IOException e) {
      e.printStackTrace();
  }
  ```
  
- 删除人脸
  ```
  //delete face by faceId
  DeleteFaceByFaceIdRequest deleteFaceByFaceIdRequest = new DeleteFaceByFaceIdRequest();
  deleteFaceByFaceIdRequest.withFaceSetName("face_set_name");
  deleteFaceByFaceIdRequest.withFaceId("iexEBb6t");
  try {
      DeleteFaceByFaceIdResponse deleteFaceByFaceIdResponse = client.deleteFaceByFaceId(deleteFaceByFaceIdRequest);
      System.out.println(deleteFaceByFaceIdResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  //delete face by externalImageId
  DeleteFaceByExternalImageIdRequest deleteFaceRequest = new DeleteFaceByExternalImageIdRequest();
  deleteFaceRequest.withFaceSetName("face_set_name");
  deleteFaceRequest.withExternalImageId("iexEBb6t");
  try {
      DeleteFaceByExternalImageIdResponse response = client.deleteFaceByExternalImageId(deleteFaceRequest);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 批量删除人脸
  ```
  BatchDeleteFacesRequest batchDeleteFacesRequest = new BatchDeleteFacesRequest();
  batchDeleteFacesRequest.withFaceSetName("face_set_name");
  DeleteFacesBatchReq deleteFacesBatchReq = new DeleteFacesBatchReq();
  deleteFacesBatchReq.withFilter("age:[20 TO 30]");
  batchDeleteFacesRequest.withBody(deleteFacesBatchReq);
  try {
      BatchDeleteFacesResponse batchDeleteFacesResponse = client.batchDeleteFaces(batchDeleteFacesRequest);
      System.out.println(batchDeleteFacesResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  示例中filter参数为string类型，用于过滤接口返回的结果信息，例如 age:\[20 TO 30\] 表示只返回20至30岁之间的人脸信息。
  
- 更新人脸
  ```
  UpdateFaceRequest updateFaceRequest = new UpdateFaceRequest();
  updateFaceRequest.withFaceSetName("face_set_name");
  UpdateFaceReq updateFaceReq = new UpdateFaceReq();
  updateFaceReq.withFaceId("iexEBb6t");
  updateFaceRequest.withBody(updateFaceReq);
  try {
      UpdateFaceResponse response = client.updateFace(updateFaceRequest);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 查询人脸
  ```
  //show faces by faceId
  ShowFacesByFaceIdRequest showFacesByFaceIdRequest = new ShowFacesByFaceIdRequest();
  showFacesByFaceIdRequest.withFaceSetName("face_set_name");
  showFacesByFaceIdRequest.withFaceId("iexEBb6t");
  try {
      ShowFacesByFaceIdResponse response = client.showFacesByFaceId(showFacesByFaceIdRequest);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  //show faces by limit
  ShowFacesByLimitRequest showFacesByLimitRequest = new ShowFacesByLimitRequest();
  showFacesByLimitRequest.withFaceSetName("face_set_name");
  showFacesByLimitRequest.withOffset(0);
  showFacesByLimitRequest.withLimit(10);
  try {
      ShowFacesByLimitResponse showFacesByLimitResponse = client.showFacesByLimit(showFacesByLimitRequest);
      System.out.println(showFacesByLimitResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  ```
  
- 动作活体检测
  ```
  //detect live by base64
  DetectLiveByBase64Request request = new DetectLiveByBase64Request();
  LiveDetectBase64Req body = new LiveDetectBase64Req();
  body.withActions("1,2,3,4");
  body.withVideoBase64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
  request.withBody(body);
  try {
      DetectLiveByBase64Response response = client.detectLiveByBase64(request);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  //detect live by file
  File file = new File("/root/video.mp4");
  try (InputStream inputStream = Files.newInputStream(file.toPath())) {
      DetectLiveByFileRequest fileRequest = new DetectLiveByFileRequest();
      DetectLiveByFileRequestBody fileRequestBody = new DetectLiveByFileRequestBody();
      fileRequestBody.setActions("2");
      fileRequestBody.withVideoFile(inputStream, file.getName());
      fileRequest.withBody(fileRequestBody);
      DetectLiveByFileResponse byFileResponse = client.detectLiveByFile(fileRequest);
      System.out.println(byFileResponse.toString());
  } catch (ConnectionException e) {
      System.out.println(e.toString());
  } catch (RequestTimeoutException e) {
      System.out.println(e.toString());
  } catch (ServiceResponseException e) {
      System.out.println(e.getErrorMsg());
  } catch (IOException e) {
      e.printStackTrace();
  }
  ```
  
- 静默活体检测
  ```
  //detect live face by base64
  DetectLiveFaceByBase64Request request = new DetectLiveFaceByBase64Request();
  LiveDetectFaceBase64Req body = new LiveDetectFaceBase64Req();
  body.withImageBase64("/9j/4AAQSkZJRgABAQAAAQABAAD...");
  request.withBody(body);
  try {
      DetectLiveFaceByBase64Response response = client.detectLiveFaceByBase64(request);
      System.out.println(response.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  }
  //detect live face by file
  DetectLiveFaceByFileRequest fileRequest = new DetectLiveFaceByFileRequest();
  DetectLiveFaceByFileRequestBody fileRequestBody = new DetectLiveFaceByFileRequestBody();
  File file = new File("/root/picture.jpg");
  try (InputStream inputStream = Files.newInputStream(file.toPath())) {
      fileRequestBody.withImageFile(inputStream, file.getName());
      fileRequest.withBody(fileRequestBody);
      DetectLiveFaceByFileResponse fileResponse = client.detectLiveFaceByFile(fileRequest);
      System.out.println(fileResponse.toString());
  } catch (ConnectionException e) {
      e.printStackTrace();
  } catch (RequestTimeoutException e) {
      e.printStackTrace();
  } catch (ServiceResponseException e) {
      e.printStackTrace();
      System.out.println(e.getHttpStatusCode());
      System.out.println(e.getErrorCode());
      System.out.println(e.getErrorMsg());
  } catch (IOException e) {
      e.printStackTrace();
  }
  ```
  
 
#### OkHttp示例
如果使用OkHttp处理HTTP请求和响应，可参考以下代码（以人脸检测为例，其它接口示例可通过[API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/sdk?product=FRS&api=DetectFaceByBase64)获取）。
```
OkHttpClient client = new OkHttpClient().newBuilder()
    .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
    .url("https://face.cn-north-4.myhuaweicloud.com/v2/{project_id}/face-detect")
    .method("POST", body)
    .addHeader("Authorization", "<Your signed string>")
    .build();
Response response = client.newCall(request).execute();
```
#### SDK代码自动生成
[API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/sdk?product=FRS&api=DetectFaceByBase64)提供API检索及平台调试，支持全量快速检索、可视化调试、帮助文档查看和在线咨询。
您只需要在API Explorer中修改接口参数，即可自动生成对应的代码示例。同时，可在集成开发环境CloudIDE中完成代码的构建、调试和运行等操作。
图4API Explorer   
![](https://support.huaweicloud.com/sdkreference-face/zh-cn_image_0000001209610029.png "点击放大")
 #### 代码运行报错
- **java.lang.NoClassDefFoundError: Could not initialize class com.huaweicloud.sdk.core.http.HttpConfig at com.huaweicloud.sdk.core.ClientBuilder.build(ClientBuilder.java:98)**
  HttpConfig 这个类在sdk-core 包里面找不到，造成原因为用户使用的sdk版本太老导致，建议使用[最新版本](https://sdkcenter.developer.huaweicloud.com/?language=java)的华为云java sdk，运行代码再具体定位。
  
- **java.lang.NoSuchFieldError: ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS**
  这个字段是 jackson-core 里面用来标识解析json格式数据是否支持前导小数点的字段，这个报错的意思是找不到这个字段，很可能是因为用户使用的jackson 版本太老导致。
  建议客户本地将jackson 版本升级到和华为云 java sdk一致，jackson版本要求请见[pom.xml](https://github.com/huaweicloud/huaweicloud-sdk-java-v3/blob/master/pom.xml)。
  引用华为云java sdk的[bundle包](https://github.com/huaweicloud/huaweicloud-sdk-java-v3/blob/master/README_CN.md)来解决 jackson 版本冲突的问题。
  ```
  <dependency>
      <groupId>com.huaweicloud.sdk</groupId>
      <artifactId>huaweicloud-sdk-bundle</artifactId>
      <version>[3.0.40-rc, 3.1.0)</version>
  </dependency>
  ```
  
- **java.lang.ClassNotFoundException: com.fasterxml.jackson.datatype.jsr310.JavaTimeModule**
  用户本地工程引入了jackson 框架，和 华为云sdk引入的jackson 框架冲突了，导致会报找不到某个类，建议 客户在本地引入[bundle包](https://github.com/huaweicloud/huaweicloud-sdk-java-v3/blob/master/README_CN.md)来避免出现依赖冲突。
  ```
  <dependency>
      <groupId>com.huaweicloud.sdk</groupId>
      <artifactId>huaweicloud-sdk-bundle</artifactId>
      <version>[3.0.40-rc, 3.1.0)</version>
  </dependency>
  ```
  
- **java.lang.ClassNotFoundException: okhttp3/Interceptor**
  用户本地引入的Okhttp3 版本和 华为云冲突，okhttp版本要求请见[pom.xml](https://github.com/huaweicloud/huaweicloud-sdk-java-v3/blob/master/pom.xml)。
  
- **INFO com.huaweicloud.sdk.core.HcClient - project id of region 'cn-north-4' not found in BasicCredentials, trying to obtain project id from IAM service: https://iam.myhuaweicloud.com**
  调用服务对应终端节点下的项目ID没有生成。
  在"[我的凭证](https://console.huaweicloud.com/iam/#/myCredential)"页面中查看对应终端节点的项目ID，确认系统中没有生成。在[FRS控制台](https://console.huaweicloud.com/frs/)将终端节点切换至调用服务所在的终端节点，之后前往"我的凭证"页面，即可查看到已生成对应的项目ID。
  
 
 #### json解析报错
图5json parse error   
![](https://support.huaweicloud.com/sdkreference-face/zh-cn_image_0000001450921225.png "点击放大")
- 服务端返回的数据格式不符合json格式，导致sdk侧解析json数据报错。
- 服务端返回的json 数据 不符合json反序列化的规则，和sdk定义的数据结构不一致，导致反序列化失败。
- sdk json 数据解析问题。
建议排查服务端返回的数据是否和服务SDK设计的结构、字段一致。
