package com.munzenberger.feed.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

public final class URLProcessor {

	private URLProcessor() {}

	public static InputStream getInputStream(URL url) throws IOException {
		
		URLConnection conn = url.openConnection();
		
		if (conn instanceof HttpURLConnection) {
			return getHttpInputStream((HttpURLConnection)conn);
		}
		else {
			return getInputStream(conn);
		}
	}
	
	private static InputStream getHttpInputStream(HttpURLConnection conn) throws IOException {
		
		int responseCode = conn.getResponseCode();
		
		// follow redirects
		if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
			String location = conn.getHeaderField("Location");
			if (location != null) {
				URL redirect = new URL(location);
				return getInputStream(redirect);
			}
		}
		
		return getInputStream(conn);
	}
	
	private static InputStream getInputStream(URLConnection conn) throws IOException {
		
		String contentEncoding = conn.getHeaderField("Content-Encoding");

		InputStream in = conn.getInputStream();
		
		// handle gzip encoded responses
		if ("gzip".equalsIgnoreCase(contentEncoding)) {
			in = new GZIPInputStream(in);
		}
		
		return in;
	}
}

@@ -356,647 +356,99 @@
 %09%0A%09%09
-URLConnection conn = url.openConnection();%0A%09%09%0A%09%09if (conn instanceof HttpURLConnection) %7B%0A%09%09%09return getHttpInputStream((HttpURLConnection)conn);%0A%09%09%7D%0A%09%09else %7B%0A%09%09%09return getInputStream(conn);%0A%09%09%7D%0A%09%7D%0A%09%0A%09private static InputStream getHttpInputStream(HttpURLConnection conn) throws IOException %7B%0A%09%09%0A%09%09int responseCode = conn.getResponseCode();%0A%09%09%0A%09%09// follow redirects%0A%09%09if (responseCode == HttpURLConnection.HTTP_MOVED_PERM %7C%7C responseCode == HttpURLConnection.HTTP_MOVED_TEMP) %7B%0A%09%09%09String location = conn.getHeaderField(%22Location%22);%0A%09%09%09if (location != null) %7B%0A%09%09%09%09URL redirect = new URL(location);%0A%09%09%09%09return getInputStream(redirect);%0A%09%09%09%7D%0A%09%09%7D
+HttpURLConnection.setFollowRedirects(true);%0A%09%09%0A%09%09URLConnection conn = url.openConnection();
 %0A%09%09%0A

use the redirect ability of the HttpURLConnection