URL url = new URL("https://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); String encoding = conn.getContentEncoding(); System.out.println("Content encoding: " + encoding);
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; URL url = new URL("https://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String encoding = conn.getContentEncoding(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); in.close(); } else { System.out.println("HTTP error: " + conn.getResponseCode()); }This code performs a GET request to "https://www.example.com", retrieves the content encoding of the response, and reads the response body as a series of lines. It uses the encoding retrieved earlier to read the InputStream containing the response body. The package library for HttpURLConnection is java.net.