This commit is contained in:
Glavo 2025-08-01 21:57:09 +08:00
parent 17aca15b2d
commit 8af0ad952d

View File

@ -115,7 +115,6 @@ public abstract class FetchTask<T> extends Task<T> {
if (conn instanceof HttpURLConnection) { if (conn instanceof HttpURLConnection) {
var httpConnection = (HttpURLConnection) conn; var httpConnection = (HttpURLConnection) conn;
redirects = new ArrayList<>();
if (checkETag) repository.injectConnection(httpConnection); if (checkETag) repository.injectConnection(httpConnection);
Map<String, List<String>> requestProperties = httpConnection.getRequestProperties(); Map<String, List<String>> requestProperties = httpConnection.getRequestProperties();
@ -131,23 +130,27 @@ public abstract class FetchTask<T> extends Task<T> {
bmclapiHash = null; bmclapiHash = null;
} }
int redirect = 0;
while (true) { while (true) {
int code = httpConnection.getResponseCode(); int code = httpConnection.getResponseCode();
if (code >= 300 && code <= 308 && code != 306 && code != 304) { if (code >= 300 && code <= 308 && code != 306 && code != 304) {
URL prevUrl = httpConnection.getURL(); if (redirects == null) {
String location = httpConnection.getHeaderField("Location"); redirects = new ArrayList<>();
httpConnection.disconnect(); } else if (redirects.size() >= 20) {
httpConnection.disconnect();
if (redirect > 20) {
throw new IOException("Too much redirects"); throw new IOException("Too much redirects");
} }
URL prevUrl = httpConnection.getURL();
String location = httpConnection.getHeaderField("Location");
httpConnection.disconnect();
if (location == null || location.isBlank()) { if (location == null || location.isBlank()) {
throw new IOException("Redirected to an empty location"); throw new IOException("Redirected to an empty location");
} }
URL target = new URL(prevUrl, NetworkUtils.encodeLocation(location)); URL target = new URL(prevUrl, NetworkUtils.encodeLocation(location));
redirects.add(target.toString()); redirects.add(target.toString());
HttpURLConnection redirected = (HttpURLConnection) target.openConnection(); HttpURLConnection redirected = (HttpURLConnection) target.openConnection();
redirected.setUseCaches(checkETag); redirected.setUseCaches(checkETag);
redirected.setConnectTimeout(NetworkUtils.TIME_OUT); redirected.setConnectTimeout(NetworkUtils.TIME_OUT);
@ -157,7 +160,6 @@ public abstract class FetchTask<T> extends Task<T> {
.forEach((key, value) -> value.forEach(element -> .forEach((key, value) -> value.forEach(element ->
redirected.addRequestProperty(key, element))); redirected.addRequestProperty(key, element)));
httpConnection = redirected; httpConnection = redirected;
redirect++;
} else { } else {
break; break;
} }