SOURCE CODE for URLRequestor applet which allows the user to enter a URL for connection
(program can be run as an applet or application)
// this program can run as an applet or an application
// load a document from a URL when a button is pressed
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class URLRequestor extends Applet {
TextField url;
TextArea textDisplay;
public static void main(String[] args) {
URLRequestor a = new URLRequestor();
Frame appletFrame = new Frame("URL Requestor");
appletFrame.add("Center", a);
appletFrame.resize(500, 300);
appletFrame.move(50, 50);
a.init();
a.start();
appletFrame.show();
}
public void init()
{
textDisplay = new TextArea();
// to keep the buttons and fields from filling the north and south sections
Panel SouthPanel = new Panel();
SouthPanel.add(new Button("Get URL"));
Panel NorthPanel = new Panel();
NorthPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
NorthPanel.add(new Label("URL: "));
url = new TextField(40);
url.setEditable( true );
NorthPanel.add(url);
setLayout(new BorderLayout());
add("South", SouthPanel);
add("Center", textDisplay);
add("North", NorthPanel);
}
public boolean action( Event e, Object o)
{
if ( e.target instanceof Button )
{
fetchURL(url.getText());
return true;
}
else if (e.target == url)
{
fetchURL(url.getText());
return true;
}
else {
return false; // event not handled yet
}
}
public void fetchURL(String str)
{
try {
URL lurl = new URL(str);
try {
Object obj = lurl.getContent();
if (obj instanceof InputStream)
{
showText ( (InputStream) obj);
}
else
{
showText (obj.toString());
}
}
catch (IOException e)
{ showText("Could not connect to " + lurl.getHost()); }
catch (NullPointerException e)
{ showText("There was a problem with the content"); }
}
catch (MalformedURLException e)
{ showText(url.getText() + "is not a valid URL"); }
}
void showText(String str)
{ textDisplay.setText(str); }
void showText (InputStream is)
{
String nextline;
textDisplay.setText("");
try {
DataInputStream dis = new DataInputStream(is);
while ((nextline = dis.readLine()) != null)
{ textDisplay.appendText(nextline + "\n"); }
}
catch (IOException e)
{ textDisplay.appendText(e.toString()); }
}
}