Google Maps Example
Home ] Up ] InfoSpace Example ] [ Google Maps Example ] Get & Post ]

 

 

Here's another example. It performs a query in a different search engine:

Did you forget to turn on Jav support in your browser?

Here's the source for the above applet:

package networking;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;

import java.net.URL;
import java.net.MalformedURLException;

import java.util.Properties;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 *   Applet to perform a query against the Lycos search engine.
 */
public class QueryApplet extends JApplet
{
  public void init()
  {
    if (!m_laidOut)
    {
      JPanel contentPanel = new JPanel();
      setContentPane(contentPanel);

      // Add the button to the applet's content pane
      contentPanel.add(m_button);
      // Set attributes of the button
      m_button.setFont( new Font("SansSerif", Font.PLAIN, 14) );
      m_button.addActionListener( new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            performQuery();
          }
        }
      );
      
      m_laidOut = true;
    }
  }
  
  /**
   *   Perform the query, firing up a new browser window.
   */
  private void performQuery()
  {
    try
    {
      // Create the base URL
      URL url = new URL("http://maps.google.com/maps");
      
      // Create the set of properties needed for the query
      Properties props = new Properties();
      props.put("f", "q");
      props.put("hl", "en");
      props.put("q", "Rivier College, Nashua, NH 03060");
      props.put("ie", "UTF8");
      props.put("z", "12");
      props.put("om", "1");
      try
      {
        // Create the final query URL
        url = URLQuery.createQuery(url, props);
System.out.println("Showing document: " + url);
        getAppletContext().showDocument(url, "_blank");
      } 
      catch (UnsupportedEncodingException ex)
      {
        ex.printStackTrace();
      } 
    }
    catch (MalformedURLException e)
    {
      e.printStackTrace();
    }
  }
  
  //// Private data ////
  private boolean m_laidOut = false;
  
  private JButton  m_button = new JButton("Google Maps Query");
}

The above applet makes use of a useful class URLQuery , which allows convenient construction of a query URL from a base URL and a set of properties:

package networking;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.MalformedURLException;

import java.util.Enumeration;
import java.util.Properties;

/**
 *   Class to create a URL to perform a CGI query against a web server.
 */
public class URLQuery
{
  /**
   *   Creates a URL query from the base URL and the set of properties.
   */
  public static URL createQuery(URL baseURL, Properties params)
      throws MalformedURLException, UnsupportedEncodingException
  {
    // Queries use the URL followed by a '?' character
    String file = baseURL.getFile() + "?";
    
    // And then append the query parameters to the URL string
    Enumeration e = params.propertyNames();
    int count = 0;
    while ( e.hasMoreElements() )
    {
      String propertyName = (String) e.nextElement();
      propertyName = URLEncoder.encode(propertyName, "UTF-8");
      if (count > 0)
        file += "&";        // Separate parameters with '&' character
      file += propertyName;
      String propertyValue = params.getProperty(propertyName);
      if (propertyValue != null)
      {
        propertyValue = URLEncoder.encode(propertyValue, "UTF-8");
        file += "=" + propertyValue;
      }
      count++;
    }
    
    return new URL(baseURL.getProtocol(), 
                   baseURL.getHost(),
                   baseURL.getPort(), 
                   file);
  }
  
  private URLQuery()
  {
    // Disable constructor
  }
}

The CGI GET and POST Methods

There are two basic methods for performing CGI queries:

  • GET, and
  • POST

The CGI GET Method

The protocol for an HTTP GET method is for the client to send the following string to the web server:

GET scriptname?parameters

followed by a blank line.

The CGI POST Method

[TBS]

The URLConnection class

Another approach is to use an HTTP-oriented class called URLConnection.

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL.

In general, creating a connection to a URL is a multistep process:

openConnection() connect()
Manipulate parameters that affect the connection to the remote resource. Interact with the resource; query header fields and contents
---------------------------->  
time  
  1. The connection object is created by invoking the openConnection method on a URL.
  2. The setup parameters and general request properties are manipulated.
  3. The actual connection to the remote object is made, using the connect method.
  4. The remote object becomes available. The header fields and the contents of the remote object can be accessed.

The setup parameters are modified using the following methods:

  • setAllowUserInteraction
  • setDoInput
  • setDoOutput
  • setIfModifiedSince
  • setUseCaches

and the general request properties are modified using the method:

  • setRequestProperty

Default values for the AllowUserInteraction and UseCaches parameters can be set using the methods setDefaultAllowUserInteraction and setDefaultUseCaches. Default values for general request properties can be set using the setDefaultRequestProperty method.

Each of the above set methods has a corresponding get method to retrieve the value of the parameter or general request property. The specific parameters and general request properties that are applicable are protocol specific.

The following methods are used to access the header fields and the contents after the connection is made to the remote object:

  • getContent
  • getHeaderField
  • getInputStream
  • getOutputStream

Certain header fields are accessed frequently. The methods:

  • getContentEncoding
  • getContentLength
  • getContentType
  • getDate
  • getExpiration
  • getLastModified

provide convenient access to these fields. The getContentType method is used by the getContent method to determine the type of the remote object; subclasses may find it convenient to override the getContentType method.

In the common case, all of the pre-connection parameters and general request properties can be ignored: the pre-connection parameters and request properties default to sensible values. For most clients of this interface, there are only two interesting methods: getInputStream and getObject, which are mirrored in the URL class by convenience methods.

Note about fileNameMap: In versions prior to JDK 1.1.6, field fileNameMap of URLConnection was public. In JDK 1.1.6 and later, fileNameMap is private; accessor method getFileNameMap() and mutator method setFileNameMap(FileNameMap) are added to access it. This change is also described on the JDK 1.1.x Compatibility page.

Reading from a URL using URLConnection

Here's the equivalent to the URLReader program we developed earlier, but using a URLConnection:

package networking;

import java.net.URL;
import java.net.URLConnection;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
*   Application to read text from a URL specified in the 
*   first command line argument, using a URLConnection
*   (Note that this is NOT a Reader in the same sense as BufferedReader.)
*/
public class URLConnectionReader
{
    public static void main(String[] args) throws Exception
    {
        URL url = new URL(args[0]);
        URLConnection conn = url.openConnection();
        BufferedReader reader = new BufferedReader(
                                        new InputStreamReader(
                                                conn.getInputStream()));
        try
        {
            String line = null;
            while (true)
            {
                line = reader.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
        }
        finally
        {
            reader.close();
        }
    }
}

Writing to a URL using URLConnection

For the HTTP protocol, writing to a URL means using CGI (Common Gateway Interface) scripts on the server.

Many CGI scripts use the POST METHOD for reading the data from the client -- hence the term posting to a URL. Server-side scripts use the POST METHOD to read from their standard input.

The following program uses a CGI script available at http://java.sun.com/cgi-bin/reverse , The script reverses any string supplied to it.

package networking;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Reverse
{
    public static void main(String[] args) throws Exception
    {
        if (args.length < 1)
        {
            System.err.println("Usage: java networking.Reverse " +
                               "<string-to-reverse>");
            return;                               
        }
        
        // Translate into x-www-form-urlencoded format:
        String reverseMe = URLEncoder.encode(args[0]);
        
        // Open connection to URL
        URL url = new URL("http://java.sun.com/cgi-bin/backwards");
        URLConnection conn = url.openConnection();
        // Set connection so it can do output
        conn.setDoOutput(true);
        
        // Provide input to server using the output stream.
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        try
        {
            out.println("string=" + reverseMe);
        }
        finally
        {
            out.close();
        }
        
        // Read response from server
        BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                            conn.getInputStream()));
        String line = null;
        try
        {
            while (true)
            {
                line = in.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
        }
        finally
        {
            in.close();
        }
    }
}

When supplied with the string:

"If it were done when 'twas done..."

this program uses the URLEncoder class to transform the string into a form acceptable to the HTTP protocol:

If+it+were+done+when+%27twas+done...

The program gets the reversed output from the server and prints it out:

...enod sawt' nehw enod erew ti fI
 
The page was last updated February 19, 2008