Code example for HttpURLConnection

Methods: getHeaderField, setConnectTimeout, setInstanceFollowRedirects, setReadTimeout, setRequestProperty

0
 
	private static SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
 
	private static HttpURLConnection connectToHttpURL(String url, int followRedirects) throws Exception, MalformedURLException {
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		connection.setRequestProperty("User-Agent", "http://jadn.com/carcast");
		connection.setConnectTimeout(30 * 1000);
		connection.setReadTimeout(20 * 1000);
		// Android seems to handle redirects improperly: 
		// the InputStream is of the redirect itself, not the redirected page 
		connection.setInstanceFollowRedirects(false);
 
		// TODO: is there a better way to properly follow redirects? 
		String redirectLocation = connection.getHeaderField("Location");
		if (redirectLocation == null || "".equals(redirectLocation)) {
			return connection;
		} 
 
		if (followRedirects == 0) {
			throw new Exception("Maximum HTTP redirects reached");
		}