Improve updater with User-Agent header & timeout

This commit is contained in:
Frank van der Heijden 2020-06-15 13:17:26 +02:00
parent c3d798c1b6
commit e93bfa6e8f
No known key found for this signature in database
GPG key ID: 26DA56488D314D11

View file

@ -58,7 +58,7 @@ public class UpdateCheckerTask implements Runnable {
JsonObject jsonObject; JsonObject jsonObject;
try { try {
jsonObject = readJsonFromURL(GITHUB_LINK).getAsJsonObject(); jsonObject = readJsonFromURL(GITHUB_LINK).getAsJsonObject();
} catch (ConnectException | UnknownHostException ex) { } catch (ConnectException | UnknownHostException | SocketTimeoutException ex) {
plugin.getLogger().severe(String.format("Error fetching new version of ServerUtils: (%s) %s (maybe check your connection?)", plugin.getLogger().severe(String.format("Error fetching new version of ServerUtils: (%s) %s (maybe check your connection?)",
ex.getClass().getSimpleName(), ex.getMessage())); ex.getClass().getSimpleName(), ex.getMessage()));
return; return;
@ -170,10 +170,11 @@ public class UpdateCheckerTask implements Runnable {
} }
private void download(String urlString, File target) throws IOException { private void download(String urlString, File target) throws IOException {
URL url = new URL(urlString); try (InputStream is = stream(urlString);
ReadableByteChannel rbc = Channels.newChannel(url.openStream()); ReadableByteChannel rbc = Channels.newChannel(is);
FileOutputStream fos = new FileOutputStream(target); FileOutputStream fos = new FileOutputStream(target)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
} }
private String readAll(BufferedReader reader) throws IOException { private String readAll(BufferedReader reader) throws IOException {
@ -186,10 +187,17 @@ public class UpdateCheckerTask implements Runnable {
} }
private JsonElement readJsonFromURL(String url) throws IOException { private JsonElement readJsonFromURL(String url) throws IOException {
try (InputStream is = new URL(url).openStream()) { try (InputStream is = stream(url)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String jsonText = readAll(reader); String jsonText = readAll(reader);
return new JsonParser().parse(jsonText); return new JsonParser().parse(jsonText);
} }
} }
private InputStream stream(String url) throws IOException {
URLConnection conn = new URL(url).openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0");
conn.setConnectTimeout(10000);
return conn.getInputStream();
}
} }