Solucionado (ver solución)
Solucionado
(ver solución)
2
respuestas

Error en client.send()

Hola, tengo un error en el IDE y no me deja compilar. El IDE subrraya el .send antes de compilar y al momento de compilar tengo un java: unreported exception java.io.IOException; must be caught or declared to be thrown

Dejo aqui mi codigo, espero puedan ayudarme.

package com.alura.screenmatch.principal;

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 PrincipalConBusqueda {
    public static void main(String[] args) {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Ingresa el nombre de la pelicula: ");
        String searchInput = keyboardInput.nextLine();

        String APIKey = "MYKEY";
        String url = "http://www.omdbapi.com/?apikey=" + APIKey + "&t=" + searchInput;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
2 respuestas
solución!

Hola Alejandro, espero te encuentres bien.

Con respecto a tu duda, el problema que estas teniendo es que no tienes agregado las excepciones. Para esto tienes dos soluciones para aplicar:

1-Cuando pones el mouse sobre .send, te va a aparecer la opcion de "add exceptions to method signature", lo que va a hacer esto es agregar throws IOException, InterruptedException al metodo (o sea quedaria public class PrincipalConBusqueda throws IOException, InterruptedException)

2- Encerrar el response dentro de un try-catch

try {
            response = client
                    .send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
}

Esto se debe de hacer debido a que .send puede llegar a devolver una excepcion, y dicha excepcion debe de ser tratada siempre.

Espero haber resuelto tu duda, un abrazo

Excelente, muchas gracias! Si se soluciono agregando el throws IOException, InterruptedException.