import java.io.*;
import java.net.*;
import java.util.*;

public class HttpRequest
{
	private HttpURLConnection  conn = null;
	private URL url = null;
	private InputStream strIn = null;

	private String responseURL = null;	//Last sucssesfull URL
	private String lastURL = null;		//Last attempted URL (Will be the same as responseURL unless a error has ocurred)
	private ArrayList<String> urls = new ArrayList<String>();	//All sucssesfull URL

	private boolean redirected = false;

	public static HttpRequest Create(String url) throws Exception
	{
		return Create( new URL(url) );
	}

	public static HttpRequest Create(URL url) throws Exception
	{
		HttpRequest hr = Create( (HttpURLConnection) url.openConnection() );
		hr.url = url;
		hr.lastURL = url.toString();
		return hr;
	}

	public static HttpRequest Create(HttpURLConnection conn) throws Exception
	{
		HttpRequest hr = new HttpRequest();
		hr.conn = conn;
		return hr;
	}

	public void close() throws IOException
	{
		strIn.close();
		conn.disconnect();
	}

	public boolean getRedirected()
	{
		return redirected;
	}

	public String getResponseURL()
	{
		return responseURL;
	}

	public String getLastURL()
	{
		return lastURL;
	}

	public String[] getJumps()
	{
		String[] array = new String[urls.size()];
		return urls.toArray(array);
	}

	public InputStream getInputStream() throws IOException
	{
		boolean redirecting = false;

		do
		{
			conn.setInstanceFollowRedirects(false);
			conn.connect();
			strIn = conn.getInputStream();

			responseURL = conn.getURL().toString();
			urls.add(responseURL);

			if( (redirecting = Redirecting(conn.getResponseCode())) )
			{
				redirected = true;
				String rURL = GetLocation(conn);
				lastURL = rURL;

				if(rURL == null)
					throw new RuntimeException("Redirected but couldn't get location");
				else if( urls.contains(rURL) )
					throw new RuntimeException("Entred Infinte Redirection Loop");

				conn = 	(HttpURLConnection) (new URL(rURL) ).openConnection();
			}
		}while(redirecting);

		return strIn;
	}

	private static boolean Redirecting(int code)
	{
		return code >= 300 && code < 400;
	}

	private static String GetLocation(HttpURLConnection  conn)
	{
		return conn.getHeaderField("Location");
	}
}