This commit is contained in:
2025-09-02 16:04:10 +08:00
parent ac1be0ef70
commit 6cec8cf580
4 changed files with 417 additions and 64 deletions

View File

@@ -11,6 +11,7 @@ import javax.crypto.spec.SecretKeySpec;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import lombok.Getter;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
@@ -24,8 +25,8 @@ public class LibLibCommon {
// API基础URL
protected static final String API_BASE_URL = "https://openapi.liblibai.cloud";
// API访问凭证
protected static final String accessKey="sOCtVLVTNOZkRMajlhzCmg"; // Access Key
protected static final String secretKey="PUe8QTRG9i0G9EbpedHmIpLQ0FyxoYY9"; // Secret Key
protected static final String accessKey = "sOCtVLVTNOZkRMajlhzCmg"; // Access Key
protected static final String secretKey = "PUe8QTRG9i0G9EbpedHmIpLQ0FyxoYY9"; // Secret Key
// 查询任务状态API路径
protected static final String QUERY_STATUS_PATH = "/api/generate/webui/status";
// 日志
@@ -46,9 +47,10 @@ public class LibLibCommon {
this.signatureNonce = signatureNonce;
}
}
/**
* 创建OkHttpClient实例
*
* @return OkHttpClient实例
*/
protected static OkHttpClient createHttpClient() {
@@ -58,19 +60,25 @@ public class LibLibCommon {
.writeTimeout(60, TimeUnit.SECONDS)
.build();
}
/**
* 生成完整的签名信息,包括签名、时间戳和随机字符串
*
* @param uri API接口的uri地址
* @return 签名信息对象
*/
public static SignatureInfo sign(String uri) {
return sign(uri, 0, null);
}
public static SignatureInfo sign(String uri, long timestamp, String signatureNonce) {
// 当前毫秒时间戳
long timestamp = System.currentTimeMillis();
if (timestamp == 0) timestamp = System.currentTimeMillis();
// 随机字符串
String signatureNonce = RandomStringUtils.randomAlphanumeric(10);
if (StrKit.isBlank(signatureNonce)) signatureNonce = RandomStringUtils.randomAlphanumeric(10);
// 拼接请求数据
String content = uri + "&" + timestamp + "&" + signatureNonce;
System.out.println(content);
try {
// 生成签名
SecretKeySpec secret = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
@@ -84,9 +92,10 @@ public class LibLibCommon {
throw new RuntimeException(e);
}
}
/**
* 清理URL移除可能的反引号和多余空格
*
* @param url 原始URL
* @return 清理后的URL
*/
@@ -96,10 +105,11 @@ public class LibLibCommon {
}
return url.trim().replace("`", "");
}
/**
* 构建带签名的URL
* @param uri API路径
*
* @param uri API路径
* @param signInfo 签名信息
* @return 构建好的HttpUrl.Builder
*/
@@ -110,47 +120,48 @@ public class LibLibCommon {
.addQueryParameter("Timestamp", String.valueOf(signInfo.getTimestamp()))
.addQueryParameter("SignatureNonce", signInfo.getSignatureNonce());
}
/**
* 发送HTTP请求并处理响应
* @param request HTTP请求
*
* @param request HTTP请求
* @param logPrefix 日志前缀
* @return 响应的JSON对象
* @throws IOException 异常信息
*/
protected static JSONObject sendRequest(Request request, String logPrefix) throws IOException {
OkHttpClient client = createHttpClient();
// 执行请求
log.info("{}: {}", logPrefix, request.url());
Response response = client.newCall(request).execute();
// 处理响应
if (!response.isSuccessful()) {
String errorMsg = logPrefix + "失败,状态码: " + response.code();
log.error(errorMsg);
throw new IOException(errorMsg);
}
// 解析响应
String responseBody = response.body().string();
log.info("{}响应: {}", logPrefix, responseBody);
JSONObject responseJson = JSON.parseObject(responseBody);
int code = responseJson.getIntValue("code");
if (code != 0) {
String errorMsg = logPrefix + "失败,错误码: " + code + ", 错误信息: " + responseJson.getString("msg");
log.error(errorMsg);
throw new IOException(errorMsg);
}
return responseJson;
}
/**
* 查询生图任务结果
*
*
* @param generateUuid 生图任务UUID
* @return 任务结果信息
* @throws IOException 异常信息
@@ -159,16 +170,16 @@ public class LibLibCommon {
// 构建请求体
JSONObject requestBody = new JSONObject();
requestBody.put("generateUuid", generateUuid);
// 获取API路径
String uri = QUERY_STATUS_PATH;
// 生成签名信息
SignatureInfo signInfo = sign(uri);
// 构建带签名的URL
HttpUrl.Builder urlBuilder = buildSignedUrl(uri, signInfo);
// 创建请求
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestBody.toJSONString());
@@ -177,16 +188,16 @@ public class LibLibCommon {
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
// 发送请求并获取响应
JSONObject responseJson = sendRequest(request, "查询生图任务结果");
return responseJson.getJSONObject("data");
}
/**
* 获取生成图片的URL列表
*
*
* @param generateUuid 生图任务UUID
* @return 图片URL列表
* @throws IOException 异常信息
@@ -194,7 +205,7 @@ public class LibLibCommon {
public static List<String> getGeneratedImageUrls(String generateUuid) throws IOException {
JSONObject resultData = queryTaskResult(generateUuid);
List<String> imageUrls = new ArrayList<>();
// 检查生成状态
int generateStatus = resultData.getIntValue("generateStatus");
if (generateStatus == 5) { // 5表示生成成功
@@ -210,26 +221,27 @@ public class LibLibCommon {
}
}
} else {
log.info("生图任务尚未完成,当前状态: {}, 完成百分比: {}%",
log.info("生图任务尚未完成,当前状态: {}, 完成百分比: {}%",
generateStatus, resultData.getIntValue("percentCompleted"));
}
return imageUrls;
}
/**
* 创建通用的HTTP请求
* @param uri API路径
*
* @param uri API路径
* @param requestBody 请求体JSON对象
* @return 构建好的Request对象
*/
protected static Request createRequest(String uri, JSONObject requestBody) {
// 生成签名信息
SignatureInfo signInfo = sign(uri);
// 构建带签名的URL
HttpUrl.Builder urlBuilder = buildSignedUrl(uri, signInfo);
// 创建请求
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, requestBody.toJSONString());
@@ -242,8 +254,8 @@ public class LibLibCommon {
public static void main(String[] args) {
String uri = "https://openapi.liblibai.cloud/api/model/version/get";
SignatureInfo signInfo = sign(uri);
SignatureInfo signInfo = sign(uri, 1756799766502L, "K91nkXyrCH");
System.out.println(signInfo.toString());
System.out.println(signInfo.getSignature());
}
}