CN Ex2
CN Ex2
NO:
DATE: Write a HTTP web client program to download a
web page using TCP Sockets.
AIM:
To create a program to use TCP sockets to establish a connection to a web server and
download a web page by sending an HTTP GET request.
ALGORITHM:
1. Obtain the URL of the web page you want to download and specify the output file
path where you want to save the downloaded content.
2. Create a URL object and parse the input URL to extract the scheme (HTTP or
HTTPS), host, and path.
3. Check if the URL uses HTTPS. If it does, proceed with HTTPS handling; otherwise)
inform the user that the example only supports HTTPS URLs.
4. Create an Https URLConnection object and set the request method to "GET".
Establish an HTTPS connection to the web server using openConnection(). Check the HTTP
response code to ensure a successful connection.
5. Create an output file stream to write the downloaded content to the specifie
output file path.
6. Read the content from the input stream in chunks and write it to the output file.
7. Close Streams and Connection: Close the output file stream, input stream, anD
HTTPS connection.
8. Display a message indicating whether the web page was successfully downloaded
or if there was an issue.
CODE:
import java.io.*;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;
if ("https".equalsIgnoreCase(parsedUrl.getProtocol())) {
httpsConnection.setRequestMethod("GET");
httpsConnection.connect();
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream is = httpsConnection.getInputStream();
int bytesRead;
fos.write(buffer, 0, bytesRead);
fos.close();
is.close();
} else {
System.out.println("Failed to download. HTTP response code: " + responseCode);
} else {
} catch (URISyntaxException e) {
} catch (IOException e) {
e.printStackTrace();
OUTPUT:
RESULT:
Thus the program to use TCP sockets to establish a connection to a web server and
download a web page by sending an HTTP GET request was executed successfully.