http -> https automatic forwarding
Pierre Fernique
Pierre.Fernique at astro.unistra.fr
Mon Feb 13 09:42:31 CET 2017
Le 11/02/2017 à 00:02, Walter Landry a écrit :
> Patrick Dowler <pdowler.cadc at gmail.com> wrote:
> (...)
>> - at least in java, redirects that change protocol are not followed
>> automatically by the http library as the design means backing out of
>> using an HttpURLConnection and instantiating an HttpsURLConnection
>> instead; iirc applications have to detect the redirect and create a
>> new URLConnection from the Location even if they told the last one to
>> follow redirects.
> That is ... really unfortunate. That sounds like it would break
> Topcat :(
>
> Thanks,
> Walter Landry
Hi,
Aladin integrates this part of Java code, that Thomas Boch found it a
few years ago, which circumvents this limitation. Feel free to integrate
it in your own code. The cited URL is now broken, but the code is
working fine.
Cheers
Pierre
/**
* Java does not follow HTTP --> HTTPS redirections by default
* This code allows to retrieve the "final" stream from a
URLConnection, after following the redirections
*
* Code copied from
http://download.oracle.com/javase/1.4.2/docs/guide/deployment/deployment-guide/upgrade-guide/article-17.html
*/
static private InputStream
openConnectionCheckRedirects(URLConnection conn) throws IOException {
boolean redir;
int redirects = 0;
InputStream in = null;
do {
if (conn instanceof HttpURLConnection) {
((HttpURLConnection) conn).setInstanceFollowRedirects(false);
}
// We want to open the input stream before getting headers
// because getHeaderField() et al swallow IOExceptions.
in = conn.getInputStream();
redir = false;
if (conn instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) conn;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 307 && stat != 306 && stat !=
HttpURLConnection.HTTP_NOT_MODIFIED) {
URL base = http.getURL();
String loc = http.getHeaderField("Location");
URL target = null;
if (loc != null) {
target = new URL(base, loc);
}
http.disconnect();
// Redirection should be allowed only for HTTP and HTTPS
// and should be limited to 5 redirections at most.
if (target == null ||
!(target.getProtocol().equals("http") ||
target.getProtocol().equals("https")) || redirects >= 5) {
throw new SecurityException("illegal URL redirect");
}
redir = true;
conn = target.openConnection();
try { conn.setUseCaches(http.getUseCaches()); } catch(
Exception e ) { }
redirects++;
}
}
} while (redir);
return in;
}
More information about the grid
mailing list