Untitled
unknown
java
3 years ago
2.2 kB
6
Indexable
// tresc zadania Zadanie 3 public class Zadanie3 { /** * Z publicznego API: https://jsonplaceholder.typicode.com pobierz wszystkie zapisane posty znajdujące się pod adresem * https://jsonplaceholder.typicode.com/posts tak by po wywołaniu metody getPosts() można było wypisać wszystkie elementy w konsoli, * podobnie jak wypisuje je przeglądarka po wejściu w link. * * Można skorzystać z dowolnych sposobów pobierania danych z API dostępnych dla języka Java. * */ public static String getPosts() { return ""; } public static void main(String[] args) { System.out.println(getPosts()); } } // moje rozwiazanie // 3rd task - Dto Class (Lombok dependency) import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @ToString @NoArgsConstructor @AllArgsConstructor public class PostDto { private long userId; private long id; private String title; private String body; } // 3rd task (Jackson dependency) import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.List; public class Main03 { private static final String POSTS_API_URL = "https://jsonplaceholder.typicode.com/posts"; public static void getPosts() throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .GET() .header("accept", "application/json") .uri(URI.create(POSTS_API_URL)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ObjectMapper mapper = new ObjectMapper(); List<PostDto> posts = mapper.readValue(response.body(), new TypeReference<>() { }); posts.forEach(System.out::println); } public static void main(String[] args) throws IOException, InterruptedException { getPosts(); } }
Editor is loading...