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.