HTTPURLConnection Doesn't Follow Redirect from HTTP to HTTPS
Redirects are followed only if they use the same protocol. (See the followRedirect()
method in the source.) There is no way to disable this check.
Even though we know it mirrors HTTP, from the HTTP protocol point of view, HTTPS is just some other, completely different, unknown protocol. It would be unsafe to follow the redirect without user approval.
For example, suppose the application is set up to perform client authentication automatically. The user expects to be surfing anonymously because he's using HTTP. But if his client follows HTTPS without asking, his identity is revealed to the server.
Http URL Connection unable to handle redirects
In HttpURLConnection
class, there is a static
method called setFollowRedirects
, here's what it's javadoc says:
Sets whether HTTP redirects (requests with response code 3xx) should
be automatically followed by this class. True by default. Applets
cannot change this variable. If there is a security manager, this
method first calls the security manager's checkSetFactory method to
ensure the operation is allowed. This could result in a
SecurityException.
By default it's always true
and hence, you will get 200 response with redirected URL. If you don't want that to happen then you need to set setFollowRedirects
to false. Below snippet demonstrates this:
URL url=new URL("https://unsplash.com/photos/65sru5g6xHk/download");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
System.out.println(httpURLConnection.getResponseCode());
if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_MOVED_TEMP){
URL redirectUrl = new URL(httpURLConnection.getHeaderField("Location"));
System.out.println(redirectUrl);
}
InputStream inptStream=httpURLConnection.getInputStream();
Output:
302
https://images.unsplash.com/photo-1488869154849-3547ed9ed8dd?ixlib=rb-0.3.5&q=100&fm=jpg&crop=entropy&cs=tinysrgb&s=b688408cbd18238a8fd1b6355e8d563d
Also, it returns 302 and not 301. So you need to use HTTP_MOVED_TEMP
constant for comparison.
Related Topics
Why Can't Overriding Methods Throw Exceptions Broader Than the Overridden Method
How to Read a Specific Line Using the Specific Line Number from a File in Java
Why Does Inetaddress.Isreachable Return False, When I Can Ping the Ip Address
How to Write a Utf-8 File with Java
Using Regex to Generate Strings Rather Than Match Them
Can Overridden Methods Differ in Return Type
How to Determine an Object's Class
The Case Against Checked Exceptions
How to Stop a Java Thread Gracefully
Reading a List from Properties File and Load with Spring Annotation @Value
How to Read and Write Xml Files
Java: Define Terms Initialization, Declaration and Assignment
Do I Need <Class> Elements in Persistence.Xml