Code example for HttpURLConnection

Methods: getResponseCode, getResponseMessage, setInstanceFollowRedirects, setRequestMethod, setRequestProperty

0
	public static String useragent;
 
	/** mainly sets the User-Agent we need */ 
	private static void setUserAgent(HttpURLConnection conn) {
		if (useragent != null)
			conn.setRequestProperty("User-Agent", useragent);
	} 
 
	public static URL getRedirectedUrl(URL url) throws IOException {
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		setUserAgent(conn);
		conn.setRequestMethod("GET");
		conn.setInstanceFollowRedirects(false);
		conn.setRequestProperty("connection", "close");
		int rc = conn.getResponseCode();
		if (rc != REDIRECT_RESPONSE_CODE) {
			throw new IOException("code " + rc + " '" + conn.getResponseMessage() + "'");
		} 
		String location = conn.getHeaderField("Location");
		if (location == null) {
			throw new IOException("No 'Location' header found");
		}