Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Last active January 24, 2023 12:48
Show Gist options
  • Save alexandreaquiles/8988fc38969d4113d7c289ed1057a459 to your computer and use it in GitHub Desktop.
Save alexandreaquiles/8988fc38969d4113d7c289ed1057a459 to your computer and use it in GitHub Desktop.
Código da Imersão Java para o TMDB
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.Map;
public class App {
public static void main(String[] args) throws Exception {
// fazer uma conexão HTTP e buscar os top 250 filmes
String url = "https://api.themoviedb.org/3/trending/movie/week?api_key=872995efee79646f5b0d834c33522673";
URI endereco = URI.create(url);
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(endereco).GET().build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String body = response.body();
// extrair só os dados que interessam (titulo, poster, classificação)
var parser = new JsonParser();
List<Map<String, String>> listaDeFilmes = parser.parse(body);
// exibir e manipular os dados
for (Map<String,String> filme : listaDeFilmes) {
System.out.println(filme.get("title"));
System.out.println(filme.get("backdrop_path"));
System.out.println(filme.get("vote_average"));
System.out.println();
}
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonParser {
private static final Pattern REGEX_ITEMS = Pattern.compile("\\[(.+)\\]");
private static final Pattern REGEX_ATRIBUTOS_JSON = Pattern.compile("\"(.+?)\":\"?(.*?)\"?,");
public List<Map<String, String>> parse(String json) {
Matcher matcher = REGEX_ITEMS.matcher(json);
if (!matcher.find()) {
throw new IllegalArgumentException("Não encontrou items.");
}
String[] items = matcher.group(1).split("\\},\\{");
List<Map<String, String>> dados = new ArrayList<>();
for (String item : items) {
Map<String, String> atributosItem = new HashMap<>();
Matcher matcherAtributosJson = REGEX_ATRIBUTOS_JSON.matcher(item);
while (matcherAtributosJson.find()) {
String atributo = matcherAtributosJson.group(1);
String valor = matcherAtributosJson.group(2);
atributosItem.put(atributo, valor);
}
dados.add(atributosItem);
}
return dados;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment