Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 網頁版
語言: 繁體中文

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.

本頁封裝的內容