Ex.No.
2 Write a HTTP web client program to download a web page using TCP
sockets.
Aim:
To write a program in java to create a socket for HTTP for web page
download.
Algorithm:
1. Start the program
2. Read the file to be downloaded from webpage
3. To download an image, use java URL class which can be found under
java.net package.
4. The file is downloaded from server and is stored in the current working
directory.
5. Stop the program
Program
Download.java
import java.io.*;
import java.net.URL;
public class Download
{
public static void main(String[] args) throws Exception
{
try
{
String fileName = "Sunflower-field-Fargo-North-
Dakota.jpg";
String website = "https://cdn.britannica.com/84/73184-
004-E5A450B5/"+fileName;
System.out.println("Downloading File From: " + website);
URL url = new URL(website);
InputStream inputStream = url.openStream();
OutputStream outputStream = new
FileOutputStream(fileName);
byte[] buffer = new byte[2048];
int length = 0;
while ((length = inputStream.read(buffer)) != -1)
{
System.out.println("Buffer Read of length: " +
length);
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
catch(Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
}
}
Output
Downloading File From:
http://tutorialspoint.com/java_dip/images/digital_image_p
rocessing.jpg
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1097
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1744
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1440
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 548
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1863
The downloaded file (Stored in the current working directory)