private static final HttpURLConnection setupConnection(URL url, boolean imposeUseragent, boolean followHttpHttpsRedirects, int cycle) throws IOException, NoSuchAlgorithmException, KeyManagementException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
if (imposeUseragent) {
connection.setRequestProperty(KEY_USERAGENT, VALUE_USERAGENT); // some feeds need this to work properly
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
if (url.getUserInfo() != null) {
connection.setRequestProperty("Authorization", "Basic "+BASE64.encode(url.getUserInfo().getBytes()));
}
connection.setRequestProperty("connection", "close"); // Workaround for android issue 7786
connection.connect();
String location = connection.getHeaderField("Location");
if (location != null && (url.getProtocol().equals(Strings._HTTP) && location.startsWith(Strings.HTTPS) || url.getProtocol().equals(Strings._HTTPS) && location.startsWith(Strings.HTTP))) {
// if location != null, the system-automatic redirect has failed which indicates a protocol change
if (followHttpHttpsRedirects) {
connection.disconnect();
if (cycle < 5) {
return setupConnection(new URL(location), imposeUseragent, followHttpHttpsRedirects, cycle+1);
} else {
throw new IOException("Too many redirects.");
}
} else {
throw new IOException("https<->http redirect - enable in settings");
}
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
if (imposeUseragent) {
connection.setRequestProperty(KEY_USERAGENT, VALUE_USERAGENT); // some feeds need this to work properly
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
if (url.getUserInfo() != null) {
connection.setRequestProperty("Authorization", "Basic "+BASE64.encode(url.getUserInfo().getBytes()));
}
connection.setRequestProperty("connection", "close"); // Workaround for android issue 7786
connection.connect();
String location = connection.getHeaderField("Location");
if (location != null && (url.getProtocol().equals(Strings._HTTP) && location.startsWith(Strings.HTTPS) || url.getProtocol().equals(Strings._HTTPS) && location.startsWith(Strings.HTTP))) {
// if location != null, the system-automatic redirect has failed which indicates a protocol change
if (followHttpHttpsRedirects) {
connection.disconnect();
if (cycle < 5) {
return setupConnection(new URL(location), imposeUseragent, followHttpHttpsRedirects, cycle+1);
} else {
throw new IOException("Too many redirects.");
}
} else {
throw new IOException("https<->http redirect - enable in settings");
}
}