The URL Class
Home ] Up ] Protocols ] Resource Names ] Absolute vs. Relative URLs ] [ The URL Class ] Reading from a URL ] Proxy Settings ]

 

 

In Java, you can use the URL class to construct a URL object.

Take a look at the API documentation for the URL class by clicking here.

Using the URL class you can construct URLs from pieces, which might involve absolute or relative URLs:

URL javasoft = new URL("http://www.javasoft.com/");
URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan, "Gamelan.game.html");
URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");
new URL("http", "www.gamelan.com", "/pages/Gamelan.net.html");
new URL("http", "www.gamelan.com", 80, "/pages/Gamelan.net.html");

Here's an example of an applet that uses this class to display a web page in another browser page:

Do you have Java turned on?

Here's the code for this applet:

package networking;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.applet.AppletContext;

import java.net.URL;
import java.net.MalformedURLException;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *   Applet to show how to cause the browser to display a URL.
 *
 *   @author Bryan J. Higgs, 9 October 1999
 */
public class ShowDocumentApplet extends JApplet
{
  public void init()
  {
    // Lay out the components, once per applet activation.
    if (!m_laidOut)
    {
      JPanel contentPane = (JPanel) getContentPane();
      contentPane.setLayout( new FlowLayout() );
      contentPane.add(m_label);
      contentPane.add(m_button);
      m_button.addActionListener( new ActionListener()
      {
        public void actionPerformed(ActionEvent event)
        {
          try
          {
            // Construct the URL
            URL javasoft = new URL("http", JAVASOFT, "");
            // Ask the browser to show the URL in a new document window.
            getAppletContext().showDocument(javasoft, "_blank");
          }
          catch (MalformedURLException e)
          {
            // Should never happen because we're
            // hardcoding a valid URL.
          }
        }
      }
      );
      
      m_laidOut = true;
    }
  }
  
  //// Private data ////
  private static final String JAVASOFT = "www.javasoft.com";
  
  private boolean  m_laidOut  = false;
  private JLabel   m_label  = new JLabel("Click to go to JavaSoft:");
  private JButton  m_button = new JButton(JAVASOFT);
}

 
The page was last updated February 19, 2008