I'm trying to import images from Internet using Java (IDE IntelliJ) but I don't know how to select an image (in this case the first of the row) from google images. For example I tried to search the capital of Rome and Napoli, but the code can't find any image from images google's section.
Probably you don't understand much what I said, so below you will find the code I wrote with the relative error
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main{
public static void main(String[] args) {
String[] listaCapitali = {
"Roma",
"Napoli",
};
for (String capitale : listaCapitali) {
ricercaGoogle("https://www.google.com/search?q=" + capitale + "+cartina&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj-moK1y-D0AhXIzaQKHeXUBLUQ_AUoAXoECAEQAw&cshid=1639392166213289&biw=2240&bih=1082&dpr=2");
}
}
private static void ricercaGoogle(String urlPath) {
try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int response = connection.getResponseCode();
System.out.println(response);
BufferedImage image = ImageIO.read(url);
FileOutputStream fos = new FileOutputStream(String.valueOf(image));
fos.write(response);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The error says:
403
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.ricercaGoogle(Main.java:33)
at Main.main(Main.java:19)
403
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.ricercaGoogle(Main.java:33)
at Main.main(Main.java:19)
Could you also help me to download those images on my computer named with the capital name? Thanks a lot