"Hi, Amigo!"
"Hi, Ellie!"
"You seem very pleased with yourself today."
"Heh, Bilaabo got sick."
"So he couldn't explain a bunch of interesting, useful, and needful things to you. It's time to put on your big-robot pants."
"Uh-huh. I promise to figure it all out myself. Bilaabo gave me a link."
"Okay, good. Then I'll tell you something interesting."
"Namely, how to download videos from the Internet."
"To work with the Internet, Java has a special class called URL. Here's how to use this class to download a file:"
1) First, you need to specify the correct URL of the server you need.
2) Then you need to use the URL to establish a connection with the server.
3) Then send the body of the request if it's a POST request. Or you can skip this step if it's a GET request.
4) Finally, read the server response.
"This is how a simple file download looks:"
URL url = new URL("https://www.google.com.ua/images/srpr/logo11w.png");
URLConnection connection = url.openConnection(); // Establish a connection
// Get an OutputStream in order to write the request to it
OutputStream outputStream = connection.getOutputStream();
outputStream.write(1);
outputStream.flush();
// Get an InputStream in order to read the response from it
InputStream inputStream = connection.getInputStream();
Files.copy(inputStream, new File("c:/google.png").toPath());
"First, we establish a connection with the server by getting a URLConnection object."
"Then we get the OutputStream that the request needs to be written to. And we write something to it."
"Then we get the InputStream object representing the response, from which we read the response itself. We use the Files.copy method to save the sent data to the file «c:/google.png»."
"Yes, I understand. What's «write(1)»?"
"Well, I included that to show you that you can write something there. You actually don't need to write anything in the request in order to download the file. You can just immediately get an InputStream and start reading the response from there. The URL object even has an openStream() method that immediately returns an InputStream object. But this is only suitable for GET requests. For example:"
URL url = new URL("https://www.google.com.ua/images/srpr/logo11w.png");
InputStream inputStream = url.openStream();
Files.copy(inputStream, new File("c:/google.png").toPath());
"How interesting! I didn't think downloading a file was so easy."
"Well, nobody usually does it like this, since files can be large and take a very long time to download."
"There are quite a few frameworks that greatly simplify working with files, but I'm not ready to talk about them now. Some other time."
GO TO FULL VERSION