301-redirect

The HttpURLConnection‘s
follow redirect is just an indicator, in fact it won’t help you to do
the “real” http redirection, you still need to handle it manually.

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setInstanceFollowRedirects(true);  //you still need to handle redirect manully.
HttpURLConnection.setFollowRedirects(true);

1. Java Http Redirect Example

If a server is redirected from the original URL to another URL, the response code should be 301: Moved Permanently or 302: Temporary Redirect. And you can get the new redirected url by reading the “Location” header of the HTTP response header.

For example, access to the normal HTTP twitter website – http://www.twitter.com , it will auto redirect to the HTTPS twitter website – https://www.twitter.com.

HttpRedirectExample – Full Java follow redirect example, see comments for self-explanatory.
package com.mkyong.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRedirectExample {

public static void main(String[] args

Tag: Nothing
Last updated:2015-11-23