URL url = new URL("https://www.example.com"); URLConnection connection = url.openConnection(); // casting to HttpURLConnection to access response code HttpURLConnection httpConnection = (HttpURLConnection) connection; int responseCode = httpConnection.getResponseCode(); String responseMessage = httpConnection.getResponseMessage(); System.out.println("Response code: " + responseCode); System.out.println("Response message: " + responseMessage);
URL url = new URL("https://www.example.com/index.html"); URLConnection connection = url.openConnection(); // read the contents of the webpage InputStream input = connection.getInputStream(); Scanner scanner = new Scanner(input); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } input.close();This example opens a connection to a URL and reads the contents of the webpage (HTML in this case) using an InputStream and a Scanner. In both examples, we used classes from the java.net package library.