Last active
January 3, 2022 17:13
-
-
Save andrewlalis/325e5c133491d8bfb1ca86c2f6684f0a to your computer and use it in GitHub Desktop.
Single-file Java script for downloading a PNG image from a URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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