From c74b2b25df75d1d1e504f0c89e46ccaee6d90cc5 Mon Sep 17 00:00:00 2001 From: Vlasenko Yevhenii Date: Mon, 6 May 2024 21:02:15 +0300 Subject: [PATCH] CharacterClient improvement --- .../rickandmorty/client/CharacterClient.java | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/src/main/java/mate/academy/rickandmorty/client/CharacterClient.java b/src/main/java/mate/academy/rickandmorty/client/CharacterClient.java index fea10898..27d5f72b 100644 --- a/src/main/java/mate/academy/rickandmorty/client/CharacterClient.java +++ b/src/main/java/mate/academy/rickandmorty/client/CharacterClient.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.URI; +import java.net.URL; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; @@ -24,22 +25,27 @@ public class CharacterClient { @Qualifier("characterMapperImpl") private final CharacterMapper mapper; - public List getAll() throws IOException, InterruptedException { - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .GET() - .uri(URI.create(URL)) - .build(); - + public List getAll() throws IOException { + HttpClient httpClient = HttpClient.newHttpClient(); ObjectMapper objectMapper = new ObjectMapper(); - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - - JsonNode rootNode = objectMapper.readTree(response.body()); - JsonNode resultsNode = rootNode.get("results"); + JsonNode resultsNode; + try { + HttpRequest request = HttpRequest.newBuilder() + .GET() + .uri(URI.create(URL)) + .build(); + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + JsonNode rootNode = objectMapper.readTree(response.body()); + resultsNode = rootNode.get("results"); + } catch (IOException | InterruptedException e) { + throw new IOException("Failed to fetch characters from external API", e); + } - List externalCharacters = objectMapper.convertValue(resultsNode, + List externalCharacters = objectMapper.readValue( + resultsNode.traverse(), new TypeReference<>() { - }); + } + ); return externalCharacters.stream() .map(mapper::toEntity)