ELECTRONICS ENGINEERINGelectronics-engineering.com
Reading from a URL with Java
Common JAVA applications take information from the Internet in order to manipulate it. To do this you need to read the content of any WEB site properly. This is a Web client…
https://www.electronics-engineering.com/en/reading-from-a-url-with-java/
Common JAVA applications take information from the Internet in order to manipulate it. To do this you need to read the content of any WEB site properly.
This is a Web client (that is, http) and the scheme to use is the following:
- Create a Url object with the desired address.
- Create a
URLConnectionobject by opening a connection to the URL - Create a chain of input streams and attach it to the connection.
- Read the Web document from this chain.
- Close the chain.
import java.net.*;
import java.io.*;
class FetchURL {
public static void main (String[] args) {
try {
URL cernHome = new URL ('https://www.electronics-engineering.com');
URLConnection cernHomeConnection = cernHome.openConnection();
BufferedReader in = new BufferedReader( new InputStreamReader (cernHomeConnection.getInputStream()));
String inputLine;
while ( (inputLine=in.readLine())!=null) {
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException e) {
System.out.println('Malformed URL Exception '+e);
} catch (IOException e ) {
System.out.println('IO Exception '+e);
}
}
}The tool’s output is printed on screen. Simple changes to this script send the output to an ascii file or to a string variable.






Benvenuti nella pagina su «Leggere da Url con Java». L'ho scritta pensando a chi studia ingegneria elettronica: se un passaggio non vi torna, un esercizio vi dà un risultato diverso o volete altro materiale sull'argomento, chiedete pure nei commenti e vi risponderò. Un voto con le stelle qui sopra mi aiuta a capire quali pagine migliorare.