Open In App

Java Program to Get Connected to a Web Server

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In today’s interconnected world, connecting to web servers is a fundamental skill for software developers. Whether you’re building a web application that needs to fetch data from external sources, testing a web service, or even performing web scraping for research, knowing how to interact with web servers programmatically is essential.

In this article, we’ll provide a comprehensive guide on how to connect to a web server using Java.

Steps for Getting Connected to the Web Server

There are certain steps to be followed to get connected with a web server as mentioned below:

Step 1: Define the URL

Before we can connect to a web server, we need to specify the URL of the server we want to interact with. This URL should point to the resource we want to access, such as a website, API endpoint, or web service. In our example, we’ll use “https://www.example.com” as a placeholder URL, but you should replace it with the URL of your choice.

Step 2: Create a URL Object

In Java, we use the URL class to work with URLs. We create a URL object by passing the URL string as a parameter to the URL constructor. This object represents the URL we want to connect to.

Step 3: Open a Connection

To establish a connection to the web server, we use the ‘HttpURLConnection’ class, which provides HTTP-specific functionality. We call the ‘openConnection()‘ method on our URL object to open a connection. We then cast the returned connection to ‘HttpURLConnection’ for HTTP-related operations.

Step 4: Set the Request Method

HTTP requests have different methods, such as GET, POST, PUT, and DELETE. In this example, we’re making a GET request to retrieve data from the server. We set the request method to “GET” using the ‘setRequestMethod(“GET”)’ method on the ‘HttpURLConnection’ object.

Step 5: Get the Response Code

To check the status of our request, we obtain the HTTP response code using the ‘getResponseCode()’ method. The response code indicates whether the request was successful or if there were any issues.

Step 6: Read and Display Response Content

To retrieve and display the content returned by the web server, we create a ‘BufferedReader’ to read the response content line by line. We append each line to a ‘StringBuilder’ to construct the complete response content. Finally, we print the response content to the console.

Program to Get Connected to Web Server

Below is the implementation of the topic mentioned below:

Java




// Java Program to get connected
// To Web Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
  
// Driver Class
public class WebServerConnection {
    // main function
    public static void main(String[] args)
    {
        try {
            // Step 1: Define the URL
            // Replace with your desired URL
            String url = "https://www.example.com";
  
            // Step 2: Create a URL object
            URL serverUrl = new URL(url);
  
            // Step 3: Open a connection
            HttpURLConnection connection
                = (HttpURLConnection)
                      serverUrl.openConnection();
  
            // Step 4: Set the request method to GET
            connection.setRequestMethod("GET");
  
            // Step 5: Get the HTTP response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: "
                               + responseCode);
  
            // Step 6: Read and display response content
            BufferedReader reader
                = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
  
            String line;
            StringBuilder responseContent
                = new StringBuilder();
  
            while ((line = reader.readLine()) != null) {
                responseContent.append(line);
            }
  
            reader.close();
  
            // Defining the file name of the file
            Path fileName = Path.of("../temp.html");
  
            // Writing into the file
            Files.writeString(fileName, responseContent.toString());
  
            // Print the response content
            System.out.println(
                "Response Content:\n"
                + responseContent.toString());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

Response Code: 200
Response Content:
<!doctype html><html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}

@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head><body><div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

In conclusion, this article has demonstrated how to create a Java program to connect to a web server using the ‘HttpURLConnection’ class. This program sends a GET request to a specified URL, retrieves the response code, and prints the response content.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads