Skip to content

Instantly share code, notes, and snippets.

@andrewlalis
Last active January 3, 2022 17:13
Show Gist options
  • Save andrewlalis/325e5c133491d8bfb1ca86c2f6684f0a to your computer and use it in GitHub Desktop.
Save andrewlalis/325e5c133491d8bfb1ca86c2f6684f0a to your computer and use it in GitHub Desktop.
Single-file Java script for downloading a PNG image from a URL
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.nio.file.Path;
class ImageScraper {
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length < 1 || args[0].isBlank()) throw new IllegalArgumentException("Missing required URL.");
String url = args[0].trim();
var request = HttpRequest.newBuilder(URI.create(url))
.GET()
.header("Accept", "image/png")
.build();
Path file; // If user supplies a second arg, use that as the filename, otherwise use "image.png"
if (args.length >= 2 && !args[1].isBlank() && args[1].endsWith(".png")) {
file = Path.of(args[1]);
} else {
file = Path.of("image.png");
}
// Send the HTTP request and download the file.
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofFile(file));
System.out.printf("Downloaded image from %s to %s.\n", url, file.toAbsolutePath());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment