Avatar ·

How to make an HTTP request in Java?

Hello everyone! Please tell me how to properly make an HTTP request (GET and POST) in pure Java without using third-party libraries like Apache HttpClient or OkHttp. I'm a beginner in Java and trying to understand network requests.

I tried using the HttpURLConnection class from the java.net package, but ran into some issues. Here is my code for a GET request:

URL url = new URL("https://api.example.com/data");\nHttpURLConnection connection = (HttpURLConnection) url.openConnection();\nconnection.setRequestMethod("GET");\nconnection.setConnectTimeout(5000);\nconnection.setReadTimeout(5000);\n\nint responseCode = connection.getResponseCode();\nSystem.out.println("Response Code: " + responseCode);\n\nBufferedReader in = new BufferedReader(new InputS