Java
Hierdie bladsy is uit Engels vertaal. As die twee verskil, is die Engelse bladsy korrek. Lees die Engelse bladsy
Die Java-biblioteek is com.getlingara:lingara-java op Maven Central. Dit vereis Java 17 of later en gebruik die JDK se eie java.net.http.HttpClient, met Jackson vir JSON.
Hoe dit lees
- Oproepe is sinchronies. Vir baie gelyktydig, laat hulle op virtuele drade of ‘n executor loop.
- ‘n Stroom is ‘n
EventStream, wat beideIterableenAutoCloseableis: lees dit met ‘nfor-lus binne try-with-resources. Gebeurtenisse is records onder ‘n sealed interface, so ‘nswitchdaaroor is uitputtend. - Om te kanselleer, onderbreek die draad of roep
close()vanaf ‘n ander draad aan. Die oproep gooi danCancellationException, wat nie een van die biblioteek se foute is nie. - Foute brei
LingaraExceptionuit, ‘n unchecked exception.retryAfter()gee ‘nOptional<Duration>terug. - Bou ‘n kliënt met
LingaraClient.builder(). ‘n Oproep wat nie stroom nie, het geen uitteltyd totdat jyrequestTimeoutstel nie.
Die voorbeelde hieronder voeg die afhanklikheid by, skep ‘n kliënt, stroom ‘n woordelys en hanteer ‘n fout.
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.