Lingara Lingara 說明文件 學習指南 API 程式庫 App 建立 網頁版
語言: 粵語

Java

呢頁係由英文翻譯過嚟嘅。如果兩個版本有出入,以英文頁為準。 睇英文頁

Java 函式庫係 Maven Central 上面嘅 com.getlingara:lingara-java。佢要 Java 17 或者更新嘅版本,用 JDK 自帶嘅 java.net.http.HttpClient,JSON 就用 Jackson 處理。

用起嚟點樣

  • 呼叫係同步嘅。要同時做好多個,就擺喺虛擬執行緒或者執行器上面行。
  • 串流係一個 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.

呢頁包裝咗乜嘢