Lingara Lingara 文档 学习指南 API 库 应用 构建 网页版
语言: 中文简体

Java

本页译自英文。如两者有出入,以英文页面为准。 阅读英文页面

Java 库是 Maven Central 上的 com.getlingara:lingara-java。它需要 Java 17 或更高版本,使用 JDK 自带的 java.net.http.HttpClient,并用 Jackson 处理 JSON。

用法一览

  • 调用是同步的。需要同时进行大量调用时,可以在虚拟线程或执行器上运行它们。
  • 流是一个 EventStream,它既是 Iterable 也是 AutoCloseable:在 try-with-resources 中用 for 循环读取它。事件是密封接口下的记录类,所以对它们的 switch 是穷尽的。
  • 要取消,可以中断线程,或从另一个线程调用 close()。此时调用会抛出 CancellationException,它不属于库的错误。
  • 错误继承自 LingaraException,这是一个非受检异常。retryAfter() 返回 Optional<Duration>。
  • 用 LingaraClient.builder() 构建客户端。不使用流的调用在你设置 requestTimeout 之前没有超时。

下面的示例会添加依赖、创建客户端、以流的方式获取词汇列表并处理错误。

Java

<dependency>
  <groupId>com.getlingara</groupId>
  <artifactId>lingara-java</artifactId>
  <version>0.1.0-alpha.6</version>
</dependency>

Java

import com.getlingara.client.LingaraClient;

LingaraClient client =
    LingaraClient.builder()
        .clientCredentials(
            System.getenv("LINGARA_CLIENT_ID"), System.getenv("LINGARA_CLIENT_SECRET"))
        .build();

Java

import com.getlingara.client.model.GenerateVocabularyEvent;
import com.getlingara.client.model.VocabRequest;

VocabRequest request = new VocabRequest().level(2).sourceLang("en").targetLang("zh").count(8);
try (EventStream<GenerateVocabularyEvent> stream = client.generateVocabulary(request)) {
  for (GenerateVocabularyEvent event : stream) {
    if (event instanceof GenerateVocabularyEvent.Item item) {
      System.out.println(item.data().getWord() + " " + item.data().getTranslation());
    }
  }
}

Java

try {
  client.getUsage();
} catch (LingaraException e) {
  if (e instanceof ApiException api) {
    // A refusal from the API: status(), code() (stable) and getMessage() (localised).
    System.out.println(api.status() + " " + api.code() + " " + api.getMessage());
    api.retryAfter().ifPresent(wait -> System.out.println("retry after " + wait));
  } else if (e instanceof OAuthException oauth) {
    // The token endpoint refused the credentials or the scopes.
    System.out.println(oauth.status() + " " + oauth.error() + " " + oauth.description());
  } else if (e instanceof MaintenanceException maintenance) {
    System.out.println("under maintenance");
    maintenance.retryAfter().ifPresent(wait -> System.out.println("retry after " + wait));
  } else if (e instanceof TransportException transport) {
    // No usable answer: CONNECT, TLS, RESET, TIMEOUT, and so on.
    System.out.println("transport: " + transport.kind());
  }
}
// An interrupted call throws java.util.concurrent.CancellationException instead.

本页封装的内容