Above everything the Java Programming language was designed to
be a Networking Language by Sun Microsystems early nineties Sun’s slogan was “The Network is the Computer”.
Actually John Gage wasn’t completely right. Although it has become true for some systems Computers are still the Computer, weather they are smartphones, smart watches, PC’s, Macs, iPads, Android tablets or Virtual Machines are still the real computers. Although they have become more and more connected and serve the API’s which are accessed trough the networks.
Public API’s are becoming more and more available and are used as services which indeed make the Network. The coming of SOA slowly is making things better.
Time to see how you can connect to a (web) service using the java.net API.
Opening and reading from a url
In java.net the Opbject which represents an url is the URL object. You can instantiate it as follows:
URL url = new URL("http://www.ejwagenaar.com");
The next step is to open a connection:
HTTPUrlConnection con = url.openConnection();
Now we are ready to read from the connection. This is similar to reading from a file:
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
This prints the html of my homepage to the console. If you want to write it to disk, follow the instructions on writing to a file.
As you can see, the methods for java.io are consistent everywhere, which makes the Java programming language easy to learn.
i/o streams should always be closed!!!
This article demonstrates how to make a http connection and read a full HTML page from an HTTP connection using only plain Java objects. In another article we will post something to the http server.