Reading Web Documents

We use a URL object for the download, and read it with an InputStreamReader and BufferedReader. The example shows the reading of a short html file on this website.

A URLConnection object offers further methods and the example shows the reading of a few lines of header data that accompany the above file download.

The code follows this screenshot of the output from the program.

Output

Output

namespace web_doc;

interface

uses
  java.io.*, java.net.*;

implementation

method ReportError(E : Exception);
begin
  System.out.println(E.toString);
  System.in.read;
  System.exit(0);
end;

var
  u : URL;
  conn : URLConnection;
  fieldname, value : String;
  br : BufferedReader;  
  isr : InputStreamReader;
  currentLine :String :='';
begin
  try
    u := new URL('http://www.pp4s.co.uk/static/pp4s/resources/RunPenApplet.html'); 
    isr := new InputStreamReader(u.openStream);
    br  := new BufferedReader(isr);
    currentLine := br.readLine;
    repeat
      writeln(currentLine);
      currentLine := br.readLine;
    until currentLine = nil;    
  except
    on E : Exception do
      ReportError(E);
  end;

  try
    conn := u.openConnection;
    for i : Integer := 1 to 6 do
      begin
        fieldname := conn.getHeaderFieldKey(i);
        value  := conn.getHeaderField(i);
        System.out.println(fieldname + ': ' + value);
      end;
  except
    on E : Exception do
      ReportError(E);
  end;
  System.in.read;  
end.

Equivalent Code in RemObjects C#

using java.util;
using java.net;
using java.io;

namespace web_doc_cs_java
{
  static class Program
  {
    private
      URL u;
      URLConnection conn;
      String fieldname, value;
      BufferedReader br;  
      InputStreamReader isr;
      String currentLine  = "";

    public void ReportError(Exception E)
    {
      System.@out.println(E.toString());
      System.@in.read();
      System.exit(0);
    }

    public void Main(string[] args)
    {
      try
      {
        u = new URL(
        "http://www.pp4s.co.uk/static/pp4s/resources/RunPenApplet.html");
        isr = new InputStreamReader(u.openStream());
        br = new BufferedReader(isr);
        currentLine = br.readLine();
        while (currentLine != null)
        {
          System.@out.println(currentLine);
          currentLine = br.readLine();
        }
      } 
      catch(Exception E)
      {
        ReportError(E);
      }

      try
      { 
        conn = u.openConnection();  
        for (Integer i  = 1 ; i <= 6; i++) 
        {
          fieldname = conn.getHeaderFieldKey(i);
          value  = conn.getHeaderField(i);
          System.@out.println(fieldname + " " + value);
        }
      }
      catch(Exception E)
      {
        ReportError(E);
      }
      System.@in.read();
      System.@in.read();
    }
  }
}
Programming - a skill for life!

How to write Oxygene for Java programs that communicate