Avatar ·

How to use java.net.URLConnection to send and handle HTTP requests

Hi everyone! I'm just starting to learn Java and encountered a task: I need to send an HTTP request to a server and get a response. I read about the URLConnection class, but I can't figure out its correct usage. I wrote the following code for a GET request: ```java import java.net.*; import java.io.*; public class HttpTest { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com/api/data"); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` But the code works unstably