Network Connections with URL’s
A Java application can create and use URL’s to anywhere; applets are restricted to URL’s to their own web server.
- String urlStr = "http://www.npac.syr.edu/";try { URL url = new URL( urlStr ); } catch ( MalformedURLException e ) { System.err.println( "Bad URL: " + urlStr );}
A method URL.openConnection() returns an instance of class URLConnection:
- URLConnection conn = url.openConnection();
- conn.connect(); // open a connection
- Now use this URLConnection object to open a stream:
- new InputStreamReader( conn.getInputStream() ) );
Applications can also use conn.getOutputStream(), but not applets.
Note that one can connect not just to HTML files but also to CGI scripts and other web documents.