HTTP requests in Java

HTTP (Hypertext Transfer Protocol) is a standard protocol used for transferring data over the web. It is the foundation of data communication on the World Wide Web and governs the communication between clients (such as web browsers) and servers.

In Java, there are various libraries and frameworks that can be used for implementing HTTP clients and servers, such as the built-in package, Apache HttpClient, and Spring Web.

Here is an example of an HTTP client implementation using the package:


public class HttpClient {
    public static void main(String[] args) {
        try {
            URL url = new URL("");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            int status = con.getResponseCode();
            System.out.println("Status code: " + status);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {

            System.out.println("Response body: " + content.toString());

        } catch (IOException e) {

In this example, we use the class to make an HTTP GET request to the URL We set the request method, connection, and read timeouts, and get the response code and response body from the server.

Here is an example of an HTTP server implementation using the Spring Web framework:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class HttpServer {
    public String hello() {
        return "Hello, World!";

    public static void main(String[] args) {, args);

In this example, we use the Spring Boot framework to create an HTTP server that listens on port 8080 and returns the string “Hello, World!” when a GET request is made to the root URL “/”. We annotate the hello() method with @GetMapping to map HTTP GET requests to that method.

HTTP protocols are used extensively in web development and building web applications, and Java provides various tools and libraries to implement HTTP clients and servers.

A quick recap of Java