From 0f53309da7f58a6b196d0a45623a3ce657151b9f Mon Sep 17 00:00:00 2001 From: Ben Fry Date: Wed, 15 Feb 2023 22:33:12 -0500 Subject: [PATCH] method for opening url streams --- app/src/processing/app/Util.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/app/src/processing/app/Util.java b/app/src/processing/app/Util.java index 7acf00432..52eb9ce79 100644 --- a/app/src/processing/app/Util.java +++ b/app/src/processing/app/Util.java @@ -23,6 +23,10 @@ package processing.app; import java.io.*; +import java.net.HttpURLConnection; +import java.net.JarURLConnection; +import java.net.URL; +import java.net.URLConnection; import java.nio.file.Files; import java.util.Enumeration; import java.util.regex.Matcher; @@ -67,6 +71,29 @@ public class Util { } + static public InputStream createInput(String path) throws IOException { + URL url = new URL(path); + URLConnection conn = url.openConnection(); + + if (conn instanceof HttpURLConnection httpConn) { + // Will not handle a protocol change (see below) + httpConn.setInstanceFollowRedirects(true); + int response = httpConn.getResponseCode(); + // Default won't follow HTTP -> HTTPS redirects for security reasons + // http://stackoverflow.com/a/1884427 + if (response >= 300 && response < 400) { + String newLocation = httpConn.getHeaderField("Location"); + return createInput(newLocation); + } + return conn.getInputStream(); + + } else if (conn instanceof JarURLConnection) { + return url.openStream(); + } + return null; + } + + /** * Read from a file with a bunch of attribute/value pairs * that are separated by = and ignore comments with #.