420 likes | 569 Views
Advanced Java Unit 3. CMSC 291 Shon Vick. Agenda. Look at URLs Summarize I/O Present some ideas about distributed computing in Java. URLs. Now lets look at URLs and which provide a relatively high-level mechanism for accessing resources on the Internet Client – uses some service
E N D
Advanced JavaUnit 3 CMSC 291 Shon Vick
Agenda • Look at URLs • Summarize I/O • Present some ideas about distributed computing in Java
URLs • Now lets look at URLs and which provide a relatively high-level mechanism for accessing resources on the Internet • Client – uses some service • Server - provides some service
Working with URLs • URL is the acronym for Uniform Resource Locator • It is a reference (an address) to a resource on the Internet. • You provide URLs to your favorite Web browser so that it can locate resources on the Internet
Properties and Uses • Java programs use a class called URL in the java.net package to represent a URL address. • Applications • You can use a URL to read in application data • Have an applet load specific web pages by having users specify a URL
Constructing a URL • Think of a URL as the name of a file on the Web because most URLs refer to a file on some machine on the network. • However, remember that URLs also can point to other resources on the network, such as database queries and other data • Consider the example in the text on pages 82-85
The anatomy of a URL • A URL has two main components • Protocol identifier • Resource name
The anatomy of a URL • The protocol identifier and the resource name are separated by a colon and two forward slashes. • The protocol identifier indicates the name of the protocol to be used to fetch the resource
Sample Protocols • Hypertext Transfer Protocol (HTTP) • Usually used to serve up hypertext documents • Other protocols include • File Transfer Protocol FTP • Gopher, File, and News
The anatomy of a Resource name • The format of the resource name depends entirely on the protocol used, but for many protocols including HTTP, the resource name contains these components • Host Name : The name of the machine on which the resource lives. • Filename: The pathname to the file on the machine
More Components of the Anatomy • Host Name : The name of the machine on which the resource lives. • Filename: The pathname to the file on the machine (sometimes implied I.e with index.html) • Port Number: The port number to which to connect (typically optional). • Reference: A named anchor within a resource that usually identifies a specific location within a file (typically optional).
Reading from and Writing to a URLConnection • Some URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require you to) write information to the URL • Example • A search script may require detailed query data to be written to the URL before the search can be performed. Let’s see how to write to a URL and how to get results back.
Reading • You can read and write to a URL • First we will look at simple examples using the URL class then we will look at examples involving the http centric URLConnection class
Creating a URL • Within your Java programs, you can create a URL object that represents a URL address • The URL object always refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL components.
URL Example • The easiest way to create a URL object is from a String that represents the human-readable form of the URL address. • Example: http://heaven.org/apply.html
Creating a URL Relative to Another • A relative URL contains only enough information to reach the resource relative to (or in the context of) another URL • Consider a html file named JoesHomePage.html (http://www.JoesPlace.com/JoesHomePage.html ) • Within this page there arelinks to other pages: <a href="PicturesOfMe.html">Pictures of Me</a>
Relative URLs • General Form • new URL(URL baseURL, String relativeURL) URL Joes = new URL (http://www.JoesPlace.com/) URLPix = new URL (Joes, “PicturesOfMe.html”) Base Relative
Other Constructs public URL(String protocol, String host, int port, String file) throws MalformedURLException public URL(String url) throws MalformedURLException public URL(String host, String file) throws MalformedURLException
MalformedURLException • Each URL constructor throws a MalformedURLException • Java does not verify to throw this exception it only checks URL specification form try { URL myURL = new URL(. . .) } catch (MalformedURLException e) { . . . // exception handler code here . . . } Good idea to catch error and deal with the error immediately
Specific Example From Book public Choice setChoiceList() {Choice ch = new Choice(); URL furl = null; DataInputStream din = null; String buf; ch.addItem("Pick One"); try { furl = new URL(getDocumentBase() + "resources.html"); } catch (MalformedURLException e) { e.printStackTrace(); ch.addItem("No Items Available"); return ch; }
Opening the URL String[] files = null; try { din = new DataInputStream(furl.openStream()); } catch( IOException e) { e.printStackTrace(); ch.addItem("No Items Available"); return ch; }
Adding the Choices try { while((buf = din.readLine()) != null) ch.addItem(buf); din.close(); } catch(IOException e) { e.printStackTrace(); ch.addItem("No Items Available"); return ch; } return ch; }
Another example import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }
Sample Explanation • When you run the program, you should see, scrolling by in your command window, the HTML commands and textual content from the HTML file located at http://www.yahoo.com/ • Alternatively, the program might hang or you might see an exception stack trace.
Sending your Applet to a URL ... String name = getParameter("Goto"); try { gotoURL = new URL(name); } catch (MalformedURLException e) { // remember to handle errors! } ... public boolean mouseDown(Event e, int x, int y) { getAppletContext().showDocument(gotoURL); return(true); }
Goto Example • Enable a browser to goto Web location • You can dynamically link providing live content with a very small amount of code • Of course you will have to add an applet tag: <applet code= GotoDemo width=300 height=200> <param name=“Goto" value=“www.gl.umbc.edu/432 > </applet> Tag
Writing to a URLConnection • Many HTML pages contain forms-- text fields and other GUI objects that let you enter data to send to the server • After you type in the required information and initiate the query by clicking a button, your Web browser writes the data to the URL over the network.
The Other End • At the other end, a cgi-bin script (usually) on the server receives the data, processes it, and then sends you a response, usually in the form of a new HTML page. • Many cgi-bin scripts use the POST METHOD for reading the data from the client. Thus writing to a URL is often called posting to a URL. Server-side scripts use the POST METHOD to read from their standard input.
Interacting With cgi-bin scripts • A Java program can interact with cgi-bin scripts also on the server side. It simply must be able to write to a URL, thus providing data to the server. • It can do this by following a few relatively steps.
The steps • .Create a URL. • Open a connection to the URL. • Set output capability on the URLConnection. • Get an output stream from the connection. This output stream is connected to the standard input stream of the cgi-bin script on the server. • Write to the output stream. • Close the output stream
Example Explanation • Say The script at our Web site reads a string from its standard input, reverses the string, and writes the result to its standard output. • The script requires input of the form string=string_to_reverse, where string_to_reverse is the string whose characters you want displayed in reverse order.
Some Sanity checking import java.io.*; import java.net.*; public class Reverse { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse " + "string_to_reverse"); System.exit(1); }
Creating the URL • Next, the program creates the URL object--the URL for the backwards script URL url = new URL("http://java.sun.com/cgi-bin/backwards"); URLConnection c = url.openConnection(); c.setDoOutput(true);
Creating the a Writer • The program then creates an output stream on the connection and opens a PrintWriter on it. • If the URL does not support output, getOutputStream method throws an UnknownServiceException. • If the URL does support output, then this method returns an output stream that is connected to the standard input stream of the URL on the server side--the client's output is the server's input PrintWriter out = new PrintWriter(c.getOutputStream());
Doing the Writing • Next, the program writes the required information to the output stream and closes the stream. • This code writes to the output stream using the println method - just like writing data to a stream. • The data written to the output stream on the client side is the input for the backwards script on the server side. out.println("string=" + stringToReverse); out.close();
Read back the results BufferReader in = new BufferedReader( new InputStreamReader(c.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close();
Output from example Reverse Me reversed is: eM esreveR
For Next Time • Read Chapters 6 and 7 about distributed processing • Finish homework
Selected References • Advanced Techniques for Java Developers Chapter 4 • http://java.sun.com/docs/books/tutorial/networking/urls/index.html • Exploring Java, O’Reilly, Niemeyer & Peck pgs.335-363 • http://userpages.umbc.edu/~vick/432/lectures/Fall98/UsingJava/Applets/MoreOnApplets.html