How to Download a File in Java

Nowadays any non trivial application written in Java would need to access cloud services over HTTP. Whether you are accessing a cloud web service or trying to download a webpage programmatically, the approach is same. Java provides a dedicated class HttpURLConnection for getting data over the HTTP protocol. The following sample Java program demonstrates the use of HttpURLConnection to download a web page. The following Java program would print the contents of Google’s home page (http://www.google.com) on the command line console.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Java program to download a web page over http protocol.
 * Requires active Internet connection.
 */
public class DownloadPage {
    
    public static void main(String[] args) {
        String pageToDownload = "http://www.google.com";
        String downloadedContent = downloadPage(pageToDownload);
        System.out.println(downloadedContent);
    }

    /**
     * Download a webpage using HttpURLConnection class.
     * @param pageToDownload
     * @return 
     */
    private static String downloadPage(String pageToDownload) {
        String result = "";
        try {
            URL url = new URL(pageToDownload);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET"); // we are getting the contents
            connection.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
              stringBuilder.append(line + "\n");
            }
            reader.close();
            result =  stringBuilder.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return result;
  }    
}

The same approach can be used to access a cloud web service returning XML or JSON data. The following sample Java program demonstrates the use of HttpURLConnection to return 7 day weather forecast of London City using the OpenWeatherMap API. The data returned is in JSON format,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Uses OpenWeatherMap API and HttpURLConnection to download 7 day weather 
 * forecast of London city in JSON format.
 */
public class WeatherDownload {
    public static void main(String[] args) {
        // Please see http://openweathermap.org/forecast16
        String weatherAPIUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=7&appid=bd82977b86bf27fb59a04b61b657fb6f";
        
        String downloadedContent = downloadWeather(weatherAPIUrl);
        System.out.println("7 day weather forecast of London city");
        System.out.println(downloadedContent);
    }

    /**
     * Access a cloud API using HttpURLConnection class.
     * @param weatherAPIUrl
     * @return 
     */
    private static String downloadWeather(String weatherAPIUrl) {
        String result = "";
        try {
            URL url = new URL(weatherAPIUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET"); // we are getting the contents
            connection.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
              stringBuilder.append(line + "\n");
            }
            reader.close();
            result =  stringBuilder.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return result;
  }    
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply