01 /*
02  * Zip.java
03  * POST zip code to look up cities.
04  *
05  * Created on April 20, 2003, 11:09 PM
06  */
07 
08 import java.io.PrintWriter;
09 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.net.URLConnection;
12 
13 import org.htmlparser.beans.StringBean;
14 
15 /**
16  * POST zip code to look up cities.
17  @author Derrick Oswald
18  */
19 public class Zip
20 {
21     String mText; // text extracted from the response to the POST request
22 
23     /**
24      * Creates a new instance of Zip
25      */
26     public Zip (String code)
27     {
28         URL url;
29         HttpURLConnection connection;
30         StringBuffer buffer;
31         PrintWriter out;
32         StringBean bean;
33 
34         try
35         {
36             // from the 'action' (relative to the refering page)
37             url = new URL ("http://www.usps.com/zip4/zip_response.jsp");
38             connection = (HttpURLConnection)url.openConnection ();
39             connection.setRequestMethod ("POST");
40 
41             connection.setDoOutput (true);
42             connection.setDoInput (true);
43             connection.setUseCaches (false);
44             
45             // more or less of these may be required
46             // see Request Header Definitions: http://www.ietf.org/rfc/rfc2616.txt
47             connection.setRequestProperty ("Accept-Charset""*");
48             connection.setRequestProperty ("Referer""http://www.usps.com/zip4/citytown.htm");
49             connection.setRequestProperty ("User-Agent""Zip.java/1.0");
50 
51             buffer = new StringBuffer (1024);
52             // 'input' fields separated by ampersands (&)
53             buffer.append ("zipcode=");
54             buffer.append (code);
55             // buffer.append ("&");
56             // etc.
57             
58             out = new PrintWriter (connection.getOutputStream ());
59             out.print (buffer);
60             out.close ();
61 
62             bean = new StringBean ();
63             bean.setConnection (connection);
64             mText = bean.getStrings ();
65         }
66         catch (Exception e)
67         {
68             mText = e.getMessage ();
69         }
70         
71     }
72     
73     public String getText ()
74     {
75         return (mText);
76     }
77 
78     /**
79      * Program mainline.
80      @param args The zip code to look up.
81      */
82     public static void main (String[] args)
83     {
84         if (>= args.length)
85             System.out.println ("Usage:  java Zip <zipcode>");
86         else
87             System.out.println (new Zip (args[0]).getText ());
88     }
89 }