Saturday, 1 November 2014

How to download a file/web page using HTTP on Android/Java

If you're using HTTP and not HTTPS, the method below is ready to go!
I'll be writing how to do it in HTTPS shortly. Please come back later ;)
private void downloadToFile(String sourceUrl, FileOutputStream destFile) throws IOException{
	URL url = new URL(sourceUrl);
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	try{
		InputStream connectionStream = new BufferedInputStream(connection.getInputStream());
		try{
			int bytesRead;
			byte[] readBuffer = new byte[1024*32];
			while((bytesRead = connectionStream.read(readBuffer)) > 0){
				destFile.write(readBuffer, 0, bytesRead);
			}
		}finally{
			connectionStream.close();
		}
	}finally{
		connection.disconnect();
	}
}

public void testDownloadWebPage() throws IOException{
	String fileName = "webpage.html";
	String webPageUrl = "http://devhelpers.blogspot.com/";
        // openFileOutput is available in the activity / context and will create a file in the app's data directory
	FileOutputStream fs = openFileOutput(fileName, Context.MODE_PRIVATE);
	try{
		client.downloadToFile(webPageUrl, fs);
	}finally{
		fs.close();
	}

}