Java SDK
本章节介绍人脸识别服务Java SDK,您可以参考本章节进行快速集成开发。
准备工作
- 注册华为账号并开通华为云,并完成实名认证,账号不能处于欠费或冻结状态。
- 已开通人脸识别服务。如未开通,请登录人脸识别管理控制台开通所需服务。
- 已具备开发环境,支持Java JDK 1.8 及其以上版本。
- 登录“我的凭证 > 访问秘钥”页面,获取Access Key(AK)和Secret Access Key(SK)。
图1 获取AK、SK
- 登录“我的凭证”页面,获取“IAM用户名”“、账号名”以及待使用区域的“项目ID”。调用服务时会用到这些信息,请提前保存。
本样例以“华北-北京四”区域为例,获取对应的项目ID(project_id)。
图2 我的凭证
安装SDK
推荐您通过Maven方式获取和安装SDK,首先需要在您的操作系统中下载并安装Maven,安装完成后您只需要在Java项目的pom.xml文件中加入相应的依赖项即可。
使用SDK前,需要安装“huaweicloud-sdk-core”和“huaweicloud-sdk-frs”依赖项。请在SDK中心获取最新的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>
当出现第三方库冲突的时,如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>
开始使用
详细的SDK介绍,使用异步客户端,配置日志请参见SDK中心、Java SDK使用指导、Java SDK使用视频。
- 导入依赖模块
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.*;
- 配置认证信息
配置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);
- 认证用的 ak 和sk 硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全。
- 本示例以 ak 和 sk 保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。
图3 Windows环境新建环境变量
- 初始化客户端
指定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; }
服务部署区域请参见终端节点。
- 发送请求并查看响应
// 以调用人脸检测 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());
使用人脸比对SDK时,image1、image2参数需为相同类型,即同为url、base64或file。
- 异常处理
表1 异常处理 一级分类
一级分类说明
二级分类
二级分类说明
ConnectionException
连接类异常
HostUnreachableException
网络不可达、被拒绝。
SslHandShakeException
SSL认证异常。
RequestTimeoutException
响应超时异常
CallTimeoutException
单次请求,服务器处理超时未返回。
RetryOutageException
在重试策略消耗完成后,仍无有效的响应。
ServiceResponseException
服务器响应异常
ServerResponseException
服务端内部错误,Http响应码:[500,]。
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 代码解析
- 人脸检测
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()); }
- 人脸比对
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()); }
- 人脸搜索
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()); }
- 创建人脸库
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 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()); }
- 删除人脸
//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 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()); }
OkHttp示例
如果使用OkHttp处理HTTP请求和响应,可参考以下代码(以人脸检测为例,其它接口示例可通过API Explorer获取)。
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提供API检索及平台调试,支持全量快速检索、可视化调试、帮助文档查看和在线咨询。
您只需要在API Explorer中修改接口参数,即可自动生成对应的代码示例。同时,可在集成开发环境CloudIDE中完成代码的构建、调试和运行等操作。
代码运行报错
- 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版本太老导致,建议使用最新版本的华为云java sdk,运行代码再具体定位。
- java.lang.NoSuchFieldError: ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS
这个字段是 jackson-core 里面用来标识解析json格式数据是否支持前导小数点的字段,这个报错的意思是找不到这个字段,很可能是因为用户使用的jackson 版本太老导致。
建议客户本地将jackson 版本升级到和华为云 java sdk一致,jackson版本要求请见pom.xml。
引用华为云java sdk的bundle包来解决 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包报来避免出现依赖冲突。
<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。
- 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没有生成。
在“我的凭证”页面中查看对应终端节点的项目ID,确认系统中没有生成。在OCR控制台将终端节点切换至调用服务所在的终端节点,之后前往“我的凭证”页面,即可查看到已生成对应的项目ID。