Java
Java SDK 发布到 Maven Central。它面向 Java 17,使用 java.net.http.HttpClient 发送请求,并依赖 Jackson 以及 JSR-305 空值注解。
安装
<dependency>
<groupId>com.your-org</groupId>
<artifactId>api-client</artifactId>
<version>1.0.0</version>
</dependency>选项
在 SDK Studio 中为 Java 设置这些选项。每个选项都会注明其对应的 octri sdk settings set键。所有语言的所有选项都列在设置参考中。
Client stylechoiceclass 会让调用方创建一个客户端。functions 会提供可导入的自由函数。请参阅客户端风格。
clientStyleByLang.java
Namespacechoice按 tags、按 URL path 对操作分组,或使用 none 不分组。
namespaceByLang.java
Method namingchoiceshort 会从方法名中省略组名,full 则保留操作 ID。可一次为所有语言设置。
methodNaming
Argument stylechoiceobject 接收一个参数对象,positional 则按顺序接收参数。请参阅参数风格。
outputByLang.java.argumentStyle
Doc commentschoicefull 或 minimal。
outputByLang.java.docComments
Usage examplechoicefull 或 concise。
outputByLang.java.usageExample
File headerchoiceinclude 或 omit。省略此项需要 Enterprise 套餐。可一次为所有语言设置。
fileHeader
软件包名称
Maven 坐标为 groupId:artifactId,groupId 必须是你拥有的域名:
com.acme:api-clientCentral 要求证明你拥有 groupId 对应的域名,并且发布版本必须签名。这比 npm 需要更多准备,最好在套餐发布之前就开始准备。
已发布的版本无法更改或删除。请参阅发布。
调用方编写的代码
var config = new SdkConfig.ClientConfig();
config.baseUrl = "https://api.acme.com/v1";
var auth = new SdkConfig.ClientAuthConfig();
auth.bearer = System.getenv("ACME_TOKEN");
config.auth = auth;
var acme = new Acme(config);
// Namespaces are final fields on the client. The callback returns false to stop.
acme.users.listPaginated(
Users.ListUsersRequest.builder().limit(100L).build(),
user -> {
System.out.println(user.id);
return true;
});请求类型嵌套在其资源类中(Users.ListUsersRequest,来自 acmeapi.methods.Users),模型公开字段。错误无需检查:每种常见状态码都是 SdkHttpError 的子类(SdkNotFoundError、SdkRateLimitError 等),并携带 statusCode 和 requestId。
运行时
| 要求 | Java 17 或更高版本 |
| HTTP | java.net.http.HttpClient |
| 超时 | 每次尝试 30 秒 |
| 重试 | 最多尝试 3 次,退避间隔从 500 ms 增至 8 秒 |
| 幂等键 | POST 和 PATCH |
流式传输
对于流式传输的操作:
try (var events = client.events.stream()) {
events.forEach(event -> System.out.println(event.id));
}返回一个 Stream<Event>。像这里这样关闭它,以释放连接。请参阅流式传输。
处理错误
try {
client.users.get(Users.GetUserRequest.builder().id("usr_1").build());
} catch (SdkNotFoundError error) {
return null;
} catch (SdkHttpError error) {
System.err.println(error.statusCode + " " + error.requestId);
throw error;
}每种常见状态码都有自己的 SdkHttpError 子类。error.data 包含解码后的模型,你可以使用 instanceof 缩窄其类型。请参阅软件包内容。