Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Last active July 1, 2021 13:05
Show Gist options
  • Save pablohdzvizcarra/7cdfff8366b1f29a4ae9f65995848b0a to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/7cdfff8366b1f29a4ae9f65995848b0a to your computer and use it in GitHub Desktop.
call api with HttpClient Java and parse json to POJO
package org.example;
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 App
{
private static final String POSTS_API_URL = "https://jsonplaceholder.typicode.com/posts";
private static final String TODO_API_URL = "https://jsonplaceholder.typicode.com/todos/1";
public static void main(String[] args)
{
HttpClient httpClient = HttpClient.newHttpClient();
ObjectMapper mapper = new ObjectMapper();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.header("accept", "application/json")
.uri(URI.create(POSTS_API_URL))
.build();
try
{
HttpResponse<String> response = httpClient.send(
request,
HttpResponse.BodyHandlers.ofString()
);
List<Post> posts =
mapper.readValue(response.body(), new TypeReference<List<Post>>()
{
});
posts
.forEach(System.out::println);
HttpRequest todoRequest = HttpRequest.newBuilder()
.GET()
.header("accept", "application/json")
.uri(URI.create(TODO_API_URL))
.build();
HttpResponse<String> todo = httpClient.send(
todoRequest,
HttpResponse.BodyHandlers.ofString()
);
Todo dataTodo = mapper.readValue(todo.body(), new TypeReference<Todo>()
{
});
System.out.println(dataTodo);
} catch (IOException | InterruptedException ioException)
{
ioException.printStackTrace();
}
System.out.println("Hello World!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment