Index Lesson One Lesson Two Lesson Three Lesson Four Lesson Five Lesson Six Lesson Seven

Lesson Seven - Networking

This applet will read URL info from a web server, and display it on the screen.

The APPLET Tag

The HTML Appplet tag is below. Notice the use of codebase.
   <APPLET
       codebase = "http://www.cs.buffalo.edu/~jjuliano/notes/net"
       code="GetURLInfoApplet.class" width=600 height=400>
   </APPLET>

Program Listing

Here is the source code:

import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;

public class GetURLInfoApplet extends Applet
{
  public void init()
  {
    this.setLayout (new BorderLayout ());
    top_panel = new Panel();
    this.add ("North", top_panel);
    {
      top_panel.setLayout (new FlowLayout (FlowLayout.CENTER, 0, 5));
      top_panel.add (new Label ("Enter URL"));
      url = new TextField (30);
      top_panel.add (url);
    }
    results = new TextArea (10,50);
    this.add ("Center", results);
    this.validate();
  }
  
  public boolean action (Event event, Object what)
  {
    if (event.target == url) {
      try {
	URL u = new URL ((String) what);
	URLConnection connection = u.openConnection();
	displayinfo (connection);
      }
      catch (Exception ex) {
	System.err.println("Exception: " + ex.getMessage());
	ex.printStackTrace();
      }
    }
    return true;
  }

  public void displayinfo(URLConnection u) throws IOException {
    // Display the URL address, and information about it.
    results.appendText (u.getURL().toExternalForm() + ":\n");
    results.appendText("  Content Type: " + u.getContentType() +"\n");
    results.appendText("  Content Length: " + u.getContentLength() +"\n");
    results.appendText("  Last Modified: " +
		       new Date(u.getLastModified()) +"\n");
    results.appendText("  Expiration: " + u.getExpiration() +"\n");
    results.appendText("  Content Encoding: " + u.getContentEncoding() +"\n");
    
    // Read and print out the first five lines of the URL.
    results.appendText("First five lines:\n");
    DataInputStream in = new DataInputStream(u.getInputStream());
    for(int i = 0; i < 5; i++) {
      String line = in.readLine();
      if (line == null) break;
      results.appendText("  " + line + "\n");
    }
    results.appendText ("\n\n");
  }
  
  protected Panel top_panel;
  protected TextField url;
  protected TextArea results;
}


Index Lesson One Lesson Two Lesson Three Lesson Four Lesson Five Lesson Six Lesson Seven