Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

[Desafio: hora da prática] Está correto?

1 - Crie um programa em Java que utilize as classes HttpClient, HttpRequest e HttpResponse para fazer uma consulta à API do Google Books. Solicite ao usuário que insira o título de um livro, e exiba as informações disponíveis sobre o livro retornado pela API.

package Challenges.exercise01;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class Service {
    Scanner scanner = new Scanner(System.in);
    Gson gson = new Gson();
    private String title = scanner.nextLine();
    private String apiKey = "";

    public String getTitle() {
        return title;
    }

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://www.googleapis.com/books/v1/volumes?q=" + title + "&maxResults=1&key=" + apiKey))
            .build();
    HttpResponse<String> response;

    {
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String responseBody = response.body();
            JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
            JsonArray items = jsonResponse.getAsJsonArray("items");
            for (int i = 0; i < items.size(); i++) {
                JsonObject item = items.get(i).getAsJsonObject();
                JsonObject volumeInfo = item.getAsJsonObject("volumeInfo");
                String title = volumeInfo.get("title").getAsString();
                String authors = volumeInfo.getAsJsonArray("authors").toString();
                System.out.println("Title: " + title + ", Authors: " + authors);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
package Challenges.exercise01;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter the name of the book you want to search for");

        Service service = new Service();
        service.getTitle();
    }
}
Saída esperada:
Enter the name of the book you want to search for
Starwars
Title: STAR WARS - Herdeiro do Império, Authors: ["Timothy Zahn"]

2 - Crie um programa Java que utiliza as classes HttpClient, HttpRequest e HttpResponse para fazer uma consulta à API CoinGecko e exiba a cotação atual de uma criptomoeda escolhida pelo usuário.

package Challenges.exercise02;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
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.Scanner;

public class Service {
    Scanner scanner = new Scanner(System.in);
    Gson gson = new Gson();
    private String criptoName = scanner.nextLine();

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.coingecko.com/api/v3/simple/price?ids=" +criptoName+ "&vs_currencies=brl"))
            .build();
    HttpResponse<String> response;

    {
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String responseBody = response.body();
            JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
            JsonObject criptoObject = jsonResponse.getAsJsonObject(criptoName);

            if (criptoObject != null) {
                // Acessa o valor em reais
                String value = criptoObject.get("brl").getAsString();
                System.out.println("Crypto: " +criptoName+
                        "\n Value: " +value);
            } else {
                System.out.println("Crypto not found: " + criptoName);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
package Challenges.exercise02;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter the cryptocurrency name to see the quote");

        var service = new Service();
    }
}
Saída esperada:
Enter the cryptocurrency name to see the quote
bitcoin
Crypto: bitcoin
 Value: 347994
2 respostas

3 - Crie um programa Java que faça uma consulta à API do TheMealDB utilizando as classes HttpClient, HttpRequest e HttpResponse. Solicite ao usuário que insira o nome de uma receita e exiba as informações disponíveis sobre essa receita.

package Challenges.exercise03;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

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.Scanner;

public class Service {
    Scanner scanner = new Scanner(System.in);
    Gson gson = new Gson();
    private String recipe = scanner.nextLine();

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://www.themealdb.com/api/json/v1/1/search.php?s=" +recipe))
            .build();
    HttpResponse<String> response;

    {
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String responseBody = response.body();
            JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
            JsonArray arrayMeals = jsonResponse.getAsJsonArray("meals");
                for (int i = 0; i < arrayMeals.size(); i++) {
                    JsonObject meal = arrayMeals.get(i).getAsJsonObject();
                    var nameRecipe = meal.get("strMeal").getAsString();
                    var category = meal.get("strCategory").getAsString();
                    var region = meal.get("strArea").getAsString();
                    var instructions = meal.get("strInstructions").getAsString();

                    System.out.println("Recipe: " +nameRecipe+
                            "\n"+
                            "\nCategory: " +category+
                            "\n"+
                            "\nRegion: " +region+
                            "\n"+
                            "\nIntructions: " +instructions);
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
package Challenges.exercise03;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter a recipe");

        var test = new Service();
    }
}
Saída esperada:
Enter a recipe
Ribollita
Recipe: Ribollita

Category: Vegetarian

Region: Italian

Intructions: Put 2 tablespoons of the oil in a large pot over medium heat. When it’s hot, add onion, carrot, celery and garlic; sprinkle with salt and pepper and cook, stirring occasionally, until vegetables are soft, 5 to 10 minutes.
Heat the oven to 500 degrees. Drain the beans; if they’re canned, rinse them as well. Add them to the pot along with tomatoes and their juices and stock, rosemary and thyme. Bring to a boil, then reduce heat so the soup bubbles steadily; cover and cook, stirring once or twice to break up the tomatoes, until the flavors meld, 15 to 20 minutes.
Fish out and discard rosemary and thyme stems, if you like, and stir in kale. Taste and adjust seasoning. Lay bread slices on top of the stew so they cover the top and overlap as little as possible. Scatter red onion slices over the top, drizzle with the remaining 3 tablespoons oil and sprinkle with Parmesan.
Put the pot in the oven and bake until the bread, onions and cheese are browned and crisp, 10 to 15 minutes. (If your pot fits under the broiler, you can also brown the top there.) Divide the soup and bread among 4 bowls and serve.
solução!

Oi, Luiz! Tudo bem?

Boa! Ótimos códigos, parabéns pela dedicação e elaboração deles! Obrigada também por tê-los compartilhado com a nossa comunidade do fórum, tenho certeza que ajudará muitos colegas! Caso surja alguma dúvida, sinta-se à vontade em comunicar por aqui, estou à disposição e ficarei super feliz em poder ajudar!

Um forte abraço e bons estudos!