Download data from an url in Java

The loadFromUrl method loads the stream from an url using the URL class. streamToString1 and streamToString2 converts the InputStream into String.

public class LoadFromUrl {
    public static String loadFromUrl(String urlStr) {
        String data="";
        try {
            URL url = new URL(urlStr);
            data = streamToString1(url.openStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
    
    private static String streamToString1(InputStream inputStream) throws IOException {
    	String data="";
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            data += inputLine + "\n";

        in.close();        	

        return data;
    }
    
    private static String streamToString2(InputStream is) throws IOException {
    	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    	byte[] buffer = new byte[1024];
    	int length;
    	
    	while ((length = is.read(buffer)) != -1) {
    		byteArrayOutputStream.write(buffer, 0, length);
    	}
    	return byteArrayOutputStream.toString("UTF-8");
    }
     
    public static void main(String args[]) {
    	long start = System.currentTimeMillis();
    	System.out.println(loadFromUrl("https://www.google.com"));
    	System.out.println("time taken: " + (System.currentTimeMillis() - start));
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search