URL url = new URL("https://example.com/api/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); InputStream inputStream = connection.getInputStream(); // Reading data from input stream BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // Closing resources reader.close(); inputStream.close(); connection.disconnect();
URL url = new URL("https://example.com/api/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); // Writing data to output stream DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); String data = "param1=value1¶m2=value2"; outputStream.writeBytes(data); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); // Reading data from input stream BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // Closing resources reader.close(); inputStream.close(); connection.disconnect();In this example, we are making a POST request to the API endpoint "https://example.com/api/data" and sending data as a query parameter. We are using a DataOutputStream to write the data to the output stream before getting the input stream to read the response data. Finally, we are closing the resources to prevent any memory leaks. Overall, java.net package provides a powerful set of libraries to make HTTP requests and handle server responses.