图像人脸鉴伪增强版
1. 接口说明
依托自研 AI 大模型算法,支持对人脸图片进行防攻击检测,可精准识别深度伪造 AI 换脸、AIGC 生成图像、高清翻拍、高仿真面具、黑灰产批量攻击、水印伪造等攻击行为,帮助业务侧的人脸核验环节筑牢可信防线。
文件要求
-
文件大小:图像文件大小30KB~5MB,图像短边>300像素,人脸短边>100像素,人脸在图像中占比>10%
-
支持格式: 支持bmp,jpg,jpeg,png,tif,tiff,webp,ppm,heif,jfif等图像格式。
接口信息
| 项目 | 说明 |
|---|---|
| Action | ImageFaceIdentifyCheck |
| 请求方法 | POST |
| 请求路径 | /openapi/v2/invoke |
| 默认版本 | V1.0 |
| 处理方式 | 默认同步 |
| 输入类型 | 图片 |
2. 调用前准备
调用方需要申请一组 AccessKey 和 AccessToken:
| 凭据 | 用途 | 是否发送 |
|---|---|---|
AccessKey | 标识调用方身份并校验 Action 权限 | 是,通过 X-RJ-Access-Key 请求头发送 |
AccessToken | 计算 HMAC-SHA256 签名 | 否,只保存在调用方服务端 |
3. 请求头
| 请求头 | 必填 | 示例 | 说明 |
|---|---|---|---|
Content-Type | 是 | application/json; charset=utf-8 | 必须与签名值完全一致 |
X-RJ-Action | 是 | ImageFaceIdentifyCheck | 固定为本接口 Action |
X-RJ-Version | 否 | V1.0 | 不传时默认 V1.0;省略时签名中的版本值为空 |
X-RJ-Access-Key | 是 | sk_xxxxxxxxxxxxxxxx | 调用方访问标识 |
X-RJ-Timestamp | 是 | 1786015888000 | Unix 毫秒时间戳,允许与服务端相差 5 分钟 |
X-RJ-Nonce | 是 | 60f84f65e86b4d60a53fa8d714d2401a | 每次请求唯一,最长 128 个字符 |
X-RJ-Content-SHA256 | 是 | 7f83b165... | 最终 HTTP Body 原始字节的 SHA-256 小写十六进制值 |
X-RJ-Signature-Method | 是 | RJ-HMAC-SHA256 | 固定值 |
X-RJ-Signature | 是 | 3a95f8bc... | 64 位小写十六进制 HMAC-SHA256 签名 |
X-RJ-Async | 是 | false | 支持 auto、true、false |
X-RJ-Async 的取值:
| 值 | 行为 |
|---|---|
auto | 默认值。请求体不超过同步阈值时同步处理,超过阈值时异步受理;强制异步 Action 始终异步 |
true | 强制异步受理,返回 taskId |
false | 强制同步;强制异步 Action 不允许使用该值 |
4 请求体
4.1 公共字段
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
idempotencyKey | String | 否(异步建议必填) | 调用方幂等键,同一业务请求重试时保持不变 |
file | Object | 是 | 待检测图片,source=url 与 source=base64 两种方式互斥 |
parameters | Object | 否 | 业务参数,见下表 |
file 字段说明
| 字段 | 说明 |
|---|---|
file.source | url 或 base64 |
file.fileUrl | 可被检测服务直接访问的 HTTP/HTTPS 文件地址(URL 方式) |
file.contentType | 文件 MIME 类型,如 image/jpeg;建议填写 |
file.filename | 原始文件名,建议包含正确后缀 |
file.content | 文件的 Base64 内容(Base64 方式),也兼容标准 Data URL |
文件大小限制:Base64 解码后的文件最大 20 MB,整个 JSON 请求体最大 30 MB;Base64 通常增加约三分之一体积,大文件建议使用
fileUrl方式。
4.2 业务参数(parameters)
| 字段 | 类型 | 必填 | 示例 | 说明 |
|---|---|---|---|---|
detAlgType | String | 否 | deepfake,liveness | 检测算法组合;单项可传 deepfake、aigc、liveness 或 black,多项用英文逗号连接且不含空格 |
config.minFace | Integer | 否 | 80 | 参与检测的最小人脸像素值 |
config.minFaceArea | Double | 否 | 0.01 | 最小人脸面积占比,建议范围 [0, 1] |
config.maxFaceArea | Double | 否 | 0.9 | 最大人脸面积占比,建议范围 [0, 1] |
config.faceNum | Integer | 否 | 1 | 参与检测的人脸数量,实际范围以算法能力为准 |
extraInfo | Object | 否 | {} | 业务场景等扩展信息 |
detAlgType 用于组合本次调用启用的检测算法。该字段为字符串而非数组;多项组合示例:deepfake,aigc、deepfake,liveness、deepfake,aigc,liveness,black。调用方无需再传 fileType、dataType 选择媒体类型。
4.3 完整请求体示例
Base64 方式
{
"idempotencyKey": "imagefaceidentifycheck-001",
"file": {
"source": "base64",
"contentType": "image/jpeg",
"filename": "portrait.jpg",
"content": "<文件的 Base64 内容>"
},
"parameters": {
"detAlgType": "deepfake,liveness",
"config": {
"minFace": 80,
"minFaceArea": 0.01,
"maxFaceArea": 0.9,
"faceNum": 1
}
}
}
fileUrl 方式
fileUrl 必须能够被 OpenAPI 服务访问。建议使用 HTTPS,并确保 URL 在任务执行期间持续有效。不要在 URL 查询参数中放置长期有效的敏感凭据。
{
"idempotencyKey": "imagefaceidentifycheck-001",
"file": {
"source": "url",
"fileUrl": "https://cdn.example.com/input/portrait.jpg",
"contentType": "image/jpeg",
"filename": "portrait.jpg"
},
"parameters": {
"detAlgType": "deepfake,liveness",
"config": {
"minFace": 80,
"minFaceArea": 0.01,
"maxFaceArea": 0.9,
"faceNum": 1
}
}
}
5. 响应说明
5.1 统一响应结构
| 字段 | 类型 | 说明 |
|---|---|---|
requestId | String | 服务端请求标识,排查问题时请提供该值 |
code | String | ErrorCodeEnums 业务码;200 表示请求成功 |
message | String | 响应说明 |
data | Object / Array / Null | 检测结果、异步任务信息或空值 |
客户端必须同时判断 HTTP 状态码和响应体 code。HTTP 200 不代表业务一定成功。
5.2 检测结果
| 字段 | 类型 | 说明 |
|---|---|---|
result | String | 检测结论:real 或 fake |
probability | Double | 人脸真实性风险概率 |
faceType | String / Null | 算法识别的人脸类型,具体取值取决于算法版本 |
detail | Object / Null | 人脸区域及算法检测明细 |
modelVersion | String / Null | 算法模型版本 |
结果示例:
{
"requestId": "req-202608070001",
"code": "200",
"message": "success",
"data": {
"result": "real",
"probability": 0.08,
"faceType": "real",
"detail": {},
"modelVersion": "V1.0"
}
}
5.3 异步受理响应
当使用 X-RJ-Async=true、auto 触发异步,或 Action 强制异步时,接口通过 data.status=QUEUED 表示任务已受理;异步受理成功的 code 仍为字符串 "200"。
{
"requestId": "req-202608070002",
"code": "200",
"message": "task accepted",
"data": {
"taskId": "task-202608070001",
"status": "QUEUED",
"callbackId": "order-20260807-0001"
}
}
5.4 异步任务查询
调用 POST /openapi/v2/tasks/query,请求体为:
{
"taskId": "task-202608070001"
}
查询请求仍使用原 Action ImageFaceIdentifyCheck,但必须针对查询路径和新请求体重新生成时间戳、Nonce、Body 摘要和签名。任务状态包括 RUNNING、SUCCEEDED、FAILED。
受理与查询的判断规则不同:
| 阶段 | 判断条件 | 客户端处理 |
|---|---|---|
| 提交受理 | HTTP 200、code="200"、data.status="QUEUED"、非空 data.taskId | 保存 taskId,再开始轮询;尚未返回检测结论 |
| 查询处理中 | HTTP 200、code="200"、顶层 status="RUNNING" | 等待后继续查询;data 可以为 null |
| 查询成功 | HTTP 200、code="200"、顶层 status="SUCCEEDED" | 停止轮询,按本接口定义读取 data;data 可以是对象、数组、标量或 null |
| 查询任务失败 | 顶层 status="FAILED" | 停止轮询并报告失败,保留 code、message、requestId 和 taskId |
| 请求限流 | HTTP 429 或业务码 A0502 | 退避后重新签名查询,不能把它当作任务失败或检测成功 |
| 其他请求错误 | HTTP 非 200 或 code!="200",例如鉴权失败、任务不存在 | 报告请求错误,修正后再查询,避免一直等到轮询超时 |
5.5 异步回调
需要服务端主动推送结果时:
- 将
X-RJ-Async设置为true。 - 同时填写
parameters.callbackId和parameters.callbackUrl。 - 填写
idempotencyKey,同一业务请求重试时保持不变。
callbackId 建议使用订单号、业务流水号或 UUID,在调用方范围内唯一,不得包含 AccessToken、身份证号等敏感信息。callbackUrl 必须是可从公网访问的 HTTP/HTTPS 绝对地址,生产环境必须使用 HTTPS,例如:
https://client.example.com/openapi/callback/ImageFaceIdentifyCheck
完整回调请求参数:
{
"idempotencyKey": "imagefaceidentifycheck-001",
"file": {
"source": "base64",
"contentType": "image/jpeg",
"filename": "portrait.jpg",
"content": "<FILE_BASE64>"
},
"parameters": {
"detAlgType": "deepfake,liveness",
"config": {
"minFace": 80,
"minFaceArea": 0.01,
"maxFaceArea": 0.9,
"faceNum": 1
},
"callbackId": "order-20260807-0001",
"callbackUrl": "https://client.example.com/openapi/callback/ImageFaceIdentifyCheck"
}
}
6. 常见错误码
| HTTP 状态码 | code | 说明 | 处理建议 |
|---|---|---|---|
| 400 | A0410 | 缺少必填请求头或参数 | 检查必填 Header 和请求字段 |
| 400 | A0400 | 请求头或媒体格式错误 | 检查时间戳、Nonce、Content-Type 和文件格式 |
| 405 | A0430 | 请求方法不支持 | 使用 POST;响应头 Allow 返回支持的方法 |
| 400 | A0427 | JSON 解析失败 | 检查请求体是否为合法 JSON |
| 200/400 | A0430 | 业务参数不合法 | 根据 message 修正文件或参数 |
| 401 | A0340 | Body 摘要、签名方式或签名值不合法 | 检查最终 Body 字节、规范请求和 AccessToken |
| 401 | A0311 | 请求时间戳过期 | 同步客户端时钟并重新生成签名 |
| 401/403 | A0301 | AccessKey 无效、已禁用或未授权 Action | 核对账号状态与能力授权 |
| 404 | A0420 | Action 或版本不存在 | 检查 X-RJ-Action 和 X-RJ-Version |
| 200 | A0600 | 异步任务不存在或不属于当前账号 | 核对 taskId 和 AccessKey |
| 409 | A0503 | Nonce 已使用 | 生成新的 Nonce、时间戳和签名后重试 |
| 413 | A0702 | 请求体超过限制 | 改用 fileUrl 或压缩文件 |
| 402 | A0203 | 账户欠费且无可用套餐余额 | 充值或购买套餐 |
| 403 | B0220 | 能力未配置可用服务档位 | 联系服务提供方开通或配置 |
| 200 | A0502 | 请求超过 QPS 限流 | 按提示指数退避重试 |
| 200 | A0501 | 请求超过日、月或总量限制 | 检查配额或联系服务提供方 |
| 200/400 | A0707 | 文件格式不受当前能力支持 | 按本 Action 支持的格式重新提交;异步任务也可能在查询时以 FAILED 返回 |
| 500 | B0001 | 服务执行异常 | 记录 requestId 后联系服务提供方 |
7. cURL 完整示例
以下 Bash 脚本会生成紧凑 JSON、Body 摘要和签名,再通过 cURL 调用接口。需要 Bash、Python 3 和 cURL。
#!/usr/bin/env bash
set -euo pipefail
: "${OPENAPI_ACCESS_KEY:?请设置 OPENAPI_ACCESS_KEY}"
: "${OPENAPI_ACCESS_TOKEN:?请设置 OPENAPI_ACCESS_TOKEN}"
MEDIA_INPUT="${1:?用法: ./invoke_image_face_identify_check.sh /path/to/portrait.jpg|https://cdn.example.com/input/portrait.jpg}"
API_URL="${OPENAPI_V2_URL:-https://openap.ruijianai.com/openapi/v2/invoke}"
ACTION="ImageFaceIdentifyCheck"
VERSION="V1.0"
CONTENT_TYPE="application/json; charset=utf-8"
SIGNED_HEADERS="content-type;x-rj-access-key;x-rj-action;x-rj-content-sha256;x-rj-nonce;x-rj-timestamp;x-rj-version"
REQUEST_FILE="request.json"
# 摘要和 HTTP 请求复用同一个文件,避免 JSON 再序列化后字节变化。
python3 - "${MEDIA_INPUT}" > "${REQUEST_FILE}" <<'PY'
import base64
import json
import mimetypes
import pathlib
import sys
import urllib.parse
import uuid
payload = {"idempotencyKey": "curl-" + uuid.uuid4().hex,
"parameters": json.loads('{"detAlgType":"deepfake,liveness","config":{"minFace":80,"minFaceArea":0.01,"maxFaceArea":0.9,"faceNum":1}}')}
media_input = sys.argv[1]
parsed = urllib.parse.urlsplit(media_input)
if parsed.scheme in ("http", "https") and parsed.netloc:
filename = pathlib.PurePosixPath(parsed.path).name or "portrait.jpg"
file_input = {"source": "url", "fileUrl": media_input,
"contentType": mimetypes.guess_type(filename)[0] or "image/jpeg",
"filename": filename}
else:
path = pathlib.Path(media_input)
if not path.is_file():
raise SystemExit(f"文件不存在: {path}")
file_input = {"source": "base64", "contentType": mimetypes.guess_type(path.name)[0] or "image/jpeg",
"filename": path.name,
"content": base64.b64encode(path.read_bytes()).decode("ascii")}
payload["file"] = file_input
sys.stdout.buffer.write(json.dumps(
payload, ensure_ascii=False, separators=(",", ":")
).encode("utf-8"))
PY
TIMESTAMP="$(python3 -c 'import time; print(int(time.time() * 1000))')"
NONCE="$(python3 -c 'import uuid; print(uuid.uuid4().hex)')"
BODY_SHA256="$(python3 -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())' "${REQUEST_FILE}")"
CANONICAL_REQUEST="$(
printf 'POST\n/openapi/v2/invoke\n\n'
printf 'content-type:%s\n' "${CONTENT_TYPE}"
printf 'x-rj-access-key:%s\n' "${OPENAPI_ACCESS_KEY}"
printf 'x-rj-action:%s\n' "${ACTION}"
printf 'x-rj-content-sha256:%s\n' "${BODY_SHA256}"
printf 'x-rj-nonce:%s\n' "${NONCE}"
printf 'x-rj-timestamp:%s\n' "${TIMESTAMP}"
printf 'x-rj-version:%s\n\n' "${VERSION}"
printf '%s\n%s' "${SIGNED_HEADERS}" "${BODY_SHA256}"
)"
CANONICAL_SHA256="$(printf '%s' "${CANONICAL_REQUEST}" | python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())')"
STRING_TO_SIGN="$(printf 'RJ-HMAC-SHA256\n%s\n%s' "${TIMESTAMP}" "${CANONICAL_SHA256}")"
SIGNATURE="$(printf '%s' "${STRING_TO_SIGN}" | python3 -c 'import hashlib,hmac,os,sys; print(hmac.new(os.environ["OPENAPI_ACCESS_TOKEN"].encode(), sys.stdin.buffer.read(), hashlib.sha256).hexdigest())')"
curl --silent --show-error --include \
--request POST "${API_URL}" \
--header "Content-Type: ${CONTENT_TYPE}" \
--header "X-RJ-Action: ${ACTION}" \
--header "X-RJ-Version: ${VERSION}" \
--header "X-RJ-Access-Key: ${OPENAPI_ACCESS_KEY}" \
--header "X-RJ-Timestamp: ${TIMESTAMP}" \
--header "X-RJ-Nonce: ${NONCE}" \
--header "X-RJ-Content-SHA256: ${BODY_SHA256}" \
--header "X-RJ-Signature-Method: RJ-HMAC-SHA256" \
--header "X-RJ-Signature: ${SIGNATURE}" \
--header "X-RJ-Async: false" \
--data-binary "@${REQUEST_FILE}"
运行前设置凭据;AccessToken 只用于本地签名,不会发送给服务端:
export OPENAPI_ACCESS_KEY="your-access-key"
export OPENAPI_ACCESS_TOKEN="your-access-token"
export OPENAPI_V2_URL="https://openap.ruijianai.com/openapi/v2/invoke"
8. Java 完整示例
示例兼容 JDK 8,使用 Jackson 生成稳定的 JSON 字节,使用 OkHttp 的共享连接池发送请求。OkHttp 通过 TLS ALPN 优先协商 HTTP/2,并在协商失败时自动回退 HTTP/1.1。
连接池参数:
| 参数 | 示例值 | 说明 |
|---|---|---|
| 最大空闲连接数 | 20 | HTTP/1.1 可复用的空闲连接上限;HTTP/2 连接可承载多个并发流 |
| 空闲连接保留时间 | 5 分钟 | 超过该时间仍未使用的空闲连接可被回收 |
| HTTP/2 PING 间隔 | 30 秒 | 检测失效的长连接;设为 0 可关闭主动 PING |
| 连接、读取、写入超时 | 10/180/180 秒 | 根据文件大小和任务响应时间调整 |
OkHttpClient 和 ConnectionPool 必须在应用生命周期内复用,不能为每次请求创建。HTTP/2 不应手工添加 Connection: keep-alive,连接复用由协议栈和连接池管理。
Maven 依赖 pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>image-face-identify-check-example</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
</dependencies>
</project>
完整代码 ImageFaceIdentifyCheckExample.java:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public final class ImageFaceIdentifyCheckExample {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String DEFAULT_URL =
"https://openap.ruijianai.com/openapi/v2/invoke";
private static final String ACTION = "ImageFaceIdentifyCheck";
private static final String VERSION = "V1.0";
private static final String CONTENT_TYPE = "application/json; charset=utf-8";
private static final String SIGN_METHOD = "RJ-HMAC-SHA256";
private static final String SIGNED_HEADERS =
"content-type;x-rj-access-key;x-rj-action;x-rj-content-sha256;"
+ "x-rj-nonce;x-rj-timestamp;x-rj-version";
private static final ConnectionPool CONNECTION_POOL =
new ConnectionPool(20, 5, TimeUnit.MINUTES);
private static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
.connectionPool(CONNECTION_POOL)
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(180, TimeUnit.SECONDS)
.writeTimeout(180, TimeUnit.SECONDS)
.pingInterval(30, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
private ImageFaceIdentifyCheckExample() {
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java ImageFaceIdentifyCheckExample /path/to/portrait.jpg|https://cdn.example.com/input/portrait.jpg");
System.exit(2);
}
byte[] body = buildRequestBody(args[0]);
HttpResult result = post("/openapi/v2/invoke", body, "false");
System.out.println(
"HTTP " + result.status + " protocol=" + result.protocol);
System.out.println(result.body);
JsonNode response = JSON.readTree(result.body);
if (result.status != 200 || !"200".equals(response.path("code").asText())) {
System.exit(1);
}
JsonNode data = response.path("data");
if (data.isObject() && "QUEUED".equals(data.path("status").asText())) {
String taskId = data.path("taskId").asText();
if (taskId.trim().isEmpty()) {
throw new IllegalStateException("Async response is missing data.taskId");
}
pollTask(taskId);
}
}
private static byte[] buildRequestBody(String input) throws Exception {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("idempotencyKey", "java-" + UUID.randomUUID());
payload.put("file", buildFileInput(input));
Map<String, Object> parameters = JSON.readValue(
"{\"detAlgType\":\"deepfake,liveness\",\"config\":{\"minFace\":80,\"minFaceArea\":0.01,\"maxFaceArea\":0.9,\"faceNum\":1}}", LinkedHashMap.class);
payload.put("parameters", parameters);
// 只序列化一次;摘要、签名和发送必须复用这份字节。
return JSON.writeValueAsBytes(payload);
}
private static Map<String, Object> buildFileInput(String input)
throws IOException {
Map<String, Object> file = new LinkedHashMap<>();
String lower = input.toLowerCase(Locale.ROOT);
if (lower.startsWith("http://") || lower.startsWith("https://")) {
URL url = new URL(input);
String filename = Paths.get(url.getPath()).getFileName().toString();
file.put("source", "url");
file.put("fileUrl", input);
file.put("contentType", "image/jpeg");
file.put("filename", filename.isEmpty() ? "portrait.jpg" : filename);
return file;
}
Path path = Paths.get(input);
if (!Files.isRegularFile(path)) {
throw new IllegalArgumentException("File not found: " + path);
}
byte[] bytes = Files.readAllBytes(path);
if (bytes.length > 20L * 1024 * 1024) {
throw new IllegalArgumentException("File exceeds 20 MB; use fileUrl");
}
file.put("source", "base64");
file.put("contentType", "image/jpeg");
file.put("filename", path.getFileName().toString());
file.put("content", Base64.getEncoder().encodeToString(bytes));
return file;
}
private static void pollTask(String taskId) throws Exception {
long deadline = System.nanoTime()
+ TimeUnit.SECONDS.toNanos(120L);
long intervalMillis = 2_000L;
long delayMillis = intervalMillis;
while (System.nanoTime() < deadline) {
long remainingMillis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime());
Thread.sleep(Math.max(1L, Math.min(delayMillis, remainingMillis)));
remainingMillis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime());
if (remainingMillis <= 0) {
break;
}
Map<String, Object> query = new LinkedHashMap<>();
query.put("taskId", taskId);
HttpResult result = post(
"/openapi/v2/tasks/query", JSON.writeValueAsBytes(query), null,
Math.min(180_000L, remainingMillis));
if (result.status == 429) {
delayMillis = Math.min(30_000L, delayMillis * 2);
System.out.println("Rate limited; retrying task=" + taskId);
continue;
}
JsonNode response = JSON.readTree(result.body);
if ("A0502".equals(response.path("code").asText())
&& !"FAILED".equals(response.path("status").asText())) {
delayMillis = Math.min(30_000L, delayMillis * 2);
System.out.println("Rate limited; retrying task=" + taskId);
continue;
}
String status = response.path("status").asText();
System.out.println("task status=" + status
+ " protocol=" + result.protocol
+ " response=" + result.body);
if (result.status != 200 || !"200".equals(response.path("code").asText())
|| "FAILED".equals(status)) {
throw new IllegalStateException("Task query failed: HTTP " + result.status
+ ", response=" + result.body);
}
if ("SUCCEEDED".equals(status)) {
return;
}
if (!"RUNNING".equals(status)) {
throw new IllegalStateException("Unexpected task status: " + status);
}
delayMillis = intervalMillis;
}
throw new IllegalStateException("Task did not finish within 120 seconds");
}
private static HttpResult post(String path, byte[] body, String asyncMode)
throws Exception {
return post(path, body, asyncMode, 180_000L);
}
private static HttpResult post(String path, byte[] body, String asyncMode, long timeoutMillis)
throws Exception {
String accessKey = requiredEnv("OPENAPI_ACCESS_KEY");
String accessToken = requiredEnv("OPENAPI_ACCESS_TOKEN");
URL invokeUrl = new URL(env("OPENAPI_V2_URL", DEFAULT_URL));
URL requestUrl = new URL(invokeUrl.getProtocol(), invokeUrl.getHost(),
invokeUrl.getPort(), path);
String timestamp = String.valueOf(System.currentTimeMillis());
String nonce = UUID.randomUUID().toString().replace("-", "");
String bodySha256 = sha256Hex(body);
String signature = signature(
path, accessKey, accessToken, timestamp, nonce, bodySha256);
Request.Builder requestBuilder = new Request.Builder()
.url(requestUrl)
.post(RequestBody.create(body, MediaType.get(CONTENT_TYPE)))
.header("Content-Type", CONTENT_TYPE)
.header("X-RJ-Action", ACTION)
.header("X-RJ-Version", VERSION)
.header("X-RJ-Access-Key", accessKey)
.header("X-RJ-Timestamp", timestamp)
.header("X-RJ-Nonce", nonce)
.header("X-RJ-Content-SHA256", bodySha256)
.header("X-RJ-Signature-Method", SIGN_METHOD)
.header("X-RJ-Signature", signature);
if (asyncMode != null) {
requestBuilder.header("X-RJ-Async", asyncMode);
}
okhttp3.Call call = HTTP_CLIENT.newCall(requestBuilder.build());
call.timeout().timeout(timeoutMillis, TimeUnit.MILLISECONDS);
try (Response response = call.execute()) {
ResponseBody responseBody = response.body();
return new HttpResult(
response.code(),
response.protocol().toString(),
responseBody == null ? "" : responseBody.string());
}
}
private static String signature(String path, String accessKey,
String accessToken, String timestamp,
String nonce, String bodySha256) throws Exception {
String canonicalHeaders =
"content-type:" + CONTENT_TYPE + "\n"
+ "x-rj-access-key:" + accessKey + "\n"
+ "x-rj-action:" + ACTION + "\n"
+ "x-rj-content-sha256:" + bodySha256 + "\n"
+ "x-rj-nonce:" + nonce + "\n"
+ "x-rj-timestamp:" + timestamp + "\n"
+ "x-rj-version:" + VERSION + "\n";
String canonicalRequest = "POST\n" + path + "\n\n"
+ canonicalHeaders + "\n" + SIGNED_HEADERS + "\n" + bodySha256;
String stringToSign = SIGN_METHOD + "\n" + timestamp + "\n"
+ sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(
accessToken.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return hex(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}
private static String sha256Hex(byte[] value) throws Exception {
return hex(MessageDigest.getInstance("SHA-256").digest(value));
}
private static String hex(byte[] value) {
StringBuilder result = new StringBuilder(value.length * 2);
for (byte item : value) {
result.append(String.format("%02x", item & 0xff));
}
return result.toString();
}
private static String requiredEnv(String name) {
String value = System.getenv(name);
if (value == null || value.trim().isEmpty()) {
throw new IllegalStateException(name + " is required");
}
return value.trim();
}
private static String env(String name, String defaultValue) {
String value = System.getenv(name);
return value == null || value.trim().isEmpty() ? defaultValue : value.trim();
}
private static final class HttpResult {
private final int status;
private final String protocol;
private final String body;
private HttpResult(int status, String protocol, String body) {
this.status = status;
this.protocol = protocol;
this.body = body;
}
}
}
编译并运行:
export OPENAPI_ACCESS_KEY="your-access-key"
export OPENAPI_ACCESS_TOKEN="your-access-token"
export OPENAPI_V2_URL="https://openap.ruijianai.com/openapi/v2/invoke"
mvn -q clean dependency:copy-dependencies package
java -cp "target/classes:target/dependency/*" ImageFaceIdentifyCheckExample /path/to/portrait.jpg
Windows 环境请将 classpath 中的冒号 : 改为分号 ;。
9. Python 完整示例
示例支持 Python 3.9 及以上版本,使用同一个 HTTPX Client 复用连接,并通过 http2=True 优先使用 HTTP/2。安装 HTTP/2 可选依赖:
python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install "httpx[http2]>=0.27.0,<1.0.0"
连接池参数:
| 参数 | 示例值 | 说明 |
|---|---|---|
max_connections | 100 | 连接池最大连接数 |
max_keepalive_connections | 20 | 允许保留的空闲长连接数 |
keepalive_expiry | 300 秒 | 空闲连接保留时间 |
pool timeout | 10 秒 | 从连接池获取连接的最长等待时间 |
httpx.Client 应在应用生命周期内复用。示例使用上下文管理器覆盖首次调用和后续任务轮询;生产服务中可把 Client 注册为单例,并在应用停止时调用 close()。不要手工添加 Connection: keep-alive,HTTP/2 不使用该连接级请求头。
完整代码 image_face_identify_check_example.py:
#!/usr/bin/env python3
"""ImageFaceIdentifyCheck 完整调用示例。"""
import base64
import hashlib
import hmac
import json
import mimetypes
import os
import sys
import time
import urllib.parse
import uuid
from pathlib import Path
import httpx
DEFAULT_URL = "https://openap.ruijianai.com/openapi/v2/invoke"
ACTION = "ImageFaceIdentifyCheck"
VERSION = "V1.0"
CONTENT_TYPE = "application/json; charset=utf-8"
SIGN_METHOD = "RJ-HMAC-SHA256"
SIGNED_HEADERS = (
"content-type;x-rj-access-key;x-rj-action;"
"x-rj-content-sha256;x-rj-nonce;x-rj-timestamp;x-rj-version"
)
def required_env(name):
value = os.getenv(name)
if not value or not value.strip():
raise RuntimeError(f"{name} is required")
return value.strip()
def create_http_client():
"""创建一个支持 HTTP/2 和连接复用的长生命周期客户端。"""
limits = httpx.Limits(
max_connections=100,
max_keepalive_connections=20,
keepalive_expiry=300.0,
)
timeout = httpx.Timeout(
connect=10.0,
read=180.0,
write=180.0,
pool=10.0,
)
return httpx.Client(
http2=True,
http1=True,
limits=limits,
timeout=timeout,
)
def build_file_input(value):
"""根据输入值构造 fileUrl 或 Base64 文件对象。"""
parsed = urllib.parse.urlsplit(value)
if parsed.scheme in ("http", "https") and parsed.netloc:
filename = Path(parsed.path).name or "portrait.jpg"
return {"source": "url", "fileUrl": value,
"contentType": mimetypes.guess_type(filename)[0] or "image/jpeg",
"filename": filename}
path = Path(value)
if not path.is_file():
raise FileNotFoundError(f"文件不存在: {path}")
content = path.read_bytes()
if len(content) > 20 * 1024 * 1024:
raise ValueError("文件超过 20 MB,请使用 fileUrl")
return {"source": "base64",
"contentType": mimetypes.guess_type(path.name)[0] or "image/jpeg",
"filename": path.name,
"content": base64.b64encode(content).decode("ascii")}
def build_request_body(input_value):
parameters = json.loads('{"detAlgType":"deepfake,liveness","config":{"minFace":80,"minFaceArea":0.01,"maxFaceArea":0.9,"faceNum":1}}')
payload = {"idempotencyKey": "python-" + uuid.uuid4().hex,
"parameters": parameters}
payload["file"] = build_file_input(input_value)
# 摘要、签名和发送都复用这一份序列化结果。
return json.dumps(payload, ensure_ascii=False,
separators=(",", ":")).encode("utf-8")
def calculate_signature(path, access_key, access_token,
timestamp, nonce, body_sha256):
canonical_headers = "".join((
f"content-type:{CONTENT_TYPE}\n",
f"x-rj-access-key:{access_key}\n",
f"x-rj-action:{ACTION}\n",
f"x-rj-content-sha256:{body_sha256}\n",
f"x-rj-nonce:{nonce}\n",
f"x-rj-timestamp:{timestamp}\n",
f"x-rj-version:{VERSION}\n",
))
canonical_request = "\n".join((
"POST", path, "", canonical_headers,
SIGNED_HEADERS, body_sha256,
))
canonical_hash = hashlib.sha256(
canonical_request.encode("utf-8")
).hexdigest()
string_to_sign = "\n".join((SIGN_METHOD, timestamp, canonical_hash))
return hmac.new(access_token.encode("utf-8"),
string_to_sign.encode("utf-8"),
hashlib.sha256).hexdigest()
def post(client, path, body, async_mode=None, timeout=180.0):
access_key = required_env("OPENAPI_ACCESS_KEY")
access_token = required_env("OPENAPI_ACCESS_TOKEN")
invoke_url = urllib.parse.urlsplit(os.getenv("OPENAPI_V2_URL", DEFAULT_URL))
request_url = urllib.parse.urlunsplit(
(invoke_url.scheme, invoke_url.netloc, path, "", "")
)
timestamp = str(int(time.time() * 1000))
nonce = uuid.uuid4().hex
body_sha256 = hashlib.sha256(body).hexdigest()
signature = calculate_signature(
path, access_key, access_token, timestamp, nonce, body_sha256
)
headers = {
"Content-Type": CONTENT_TYPE,
"X-RJ-Action": ACTION,
"X-RJ-Version": VERSION,
"X-RJ-Access-Key": access_key,
"X-RJ-Timestamp": timestamp,
"X-RJ-Nonce": nonce,
"X-RJ-Content-SHA256": body_sha256,
"X-RJ-Signature-Method": SIGN_METHOD,
"X-RJ-Signature": signature,
}
if async_mode is not None:
headers["X-RJ-Async"] = async_mode
response = client.post(
request_url, content=body, headers=headers,
timeout=httpx.Timeout(timeout, connect=min(10.0, timeout), pool=min(10.0, timeout)),
)
if response.status_code == 429:
return response.status_code, {"message": "HTTP rate limit"}, response.http_version
payload = response.json()
if not isinstance(payload, dict):
raise RuntimeError("响应JSON必须是对象")
return response.status_code, payload, response.http_version
def poll_task(client, task_id):
deadline = time.monotonic() + 120
delay = 2
while time.monotonic() < deadline:
time.sleep(min(delay, max(0, deadline - time.monotonic())))
remaining = deadline - time.monotonic()
if remaining <= 0:
break
body = json.dumps({"taskId": task_id},
separators=(",", ":")).encode("utf-8")
http_status, response, http_version = post(
client, "/openapi/v2/tasks/query", body, timeout=min(180.0, remaining)
)
if time.monotonic() >= deadline:
break
if http_status == 429 or (response.get("code") == "A0502" and response.get("status") != "FAILED"):
delay = min(30, delay * 2)
print(f"限流,稍后重试 task={task_id}")
continue
status = response.get("status")
print(f"HTTP {http_status} protocol={http_version} task={status}")
print(json.dumps(response, ensure_ascii=False, indent=2))
if http_status != 200 or response.get("code") != "200" or status == "FAILED":
raise RuntimeError(f"任务查询失败: {response}")
if status == "SUCCEEDED":
return response
if status != "RUNNING":
raise RuntimeError(f"任务状态缺失或非法: {status}")
delay = 2
raise TimeoutError("任务在 120 秒内未完成")
def main():
if len(sys.argv) != 2:
print("用法: python3 image_face_identify_check_example.py /path/to/portrait.jpg|https://cdn.example.com/input/portrait.jpg", file=sys.stderr)
return 2
body = build_request_body(sys.argv[1])
with create_http_client() as client:
http_status, response, http_version = post(
client, "/openapi/v2/invoke", body, "false"
)
print(f"HTTP {http_status} protocol={http_version}")
print(json.dumps(response, ensure_ascii=False, indent=2))
if http_status != 200 or response.get("code") != "200":
return 1
data = response.get("data")
if isinstance(data, dict) and data.get("status") == "QUEUED":
task_id = data.get("taskId")
if not isinstance(task_id, str) or not task_id.strip():
raise RuntimeError("异步受理响应缺少data.taskId")
poll_task(client, task_id)
return 0
if __name__ == "__main__":
sys.exit(main())
运行:
export OPENAPI_ACCESS_KEY="your-access-key"
export OPENAPI_ACCESS_TOKEN="your-access-token"
export OPENAPI_V2_URL="https://openap.ruijianai.com/openapi/v2/invoke"
python3 image_face_identify_check_example.py /path/to/portrait.jpg
10. 接入检查清单
- AccessToken 仅保存在调用方服务端,不发送给 OpenAPI,也不进入前端代码和日志。
- 客户端时钟已同步;每次请求生成新的毫秒时间戳和 Nonce。
- 先生成最终 Body 字节,再计算
X-RJ-Content-SHA256和签名,随后原样发送。 Content-Type、Action、版本和参与签名的实际请求头值完全一致。- 不把 Host 或
X-RJ-Async放入签名头列表。 - Base64 输入不传
file.encoding;大文件优先使用可访问且有效期足够的fileUrl。 - 异步请求填写幂等键;轮询设置合理间隔,避免高频查询。
- 在应用生命周期内复用 OkHttpClient 或 HTTPX Client,不为每次请求创建新连接池。
- HTTP/2 不手工设置
Connection: keep-alive;通过客户端输出确认实际协商协议。 - 回调同时填写
callbackId和callbackUrl,接收端按 taskId 或 callbackId 做幂等。 - 同时检查 HTTP 状态码和响应体
code,并记录失败请求的requestId。 - 对限流、网络超时和可重试的服务错误使用指数退避,重试时重新签名。









