What is HttpURLConnection (legacy) in Java?

HttpURLConnection is a class in Java that allows developers to send HTTP requests and receive HTTP responses from a URL. It is part of the java.net package and provides an easy way to interact with web services and REST APIs. HttpURLConnection is a legacy class that is widely used for making HTTP calls in Java applications, ensuring that developers can handle GET, POST, PUT, and DELETE requests with minimal overhead.

Example of HttpURLConnection Usage

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) { try { URL url = new URL("https://api.example.com/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("Response: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } }

HttpURLConnection Java HTTP requests web services REST APIs legacy class